Home > Mobile >  Can you set the property of a Python class equal to an empty class object?
Can you set the property of a Python class equal to an empty class object?

Time:11-15

I have a player class and a weapon class. The weapon class has a reload method that checks the inventory property of the player. The player class has a weapon property that would hold the current weapon object, from which the reload method would be called. Since the player can change weapons, I would like to instantiate the player object without a weapon object, but have access to weapon object intellisense in development. Is this possible?

In short, I'd like to be able to see the methods of my weapon class from within my player class, without an instance being created.

CodePudding user response:

Why not use a dummy weapon object that the player holds when they're not holding a weapon? It can be an invisible weapon and lets you access whatever you want in this context.

If it'll mess with the unarmed state, you can make the player use unarmed attack animations if that's needed.

CodePudding user response:

You could make use of __dict__, to get all attributes of a class:

class Player:
    def __init__(self, name):
        self.name = name
        self.weapon = None

    def weaponsAvailable(self):
        print([w for w, _ in Weapon.__dict__.items() if not w.startswith('__')])


class Weapon:
    def gun(self):
        print('gun')

    def knife(self):
        print('knife')


p = Player('Player1')
p.weaponsAvailable()

Out:

['gun', 'knife']
  • Related