我正在使用 OOP 编写我的第一个 python 游戏,我在访问类变量方面遇到了一些问题。 具体来说,我想从一个方法中访问一个类变量。对于某些变量它有效,但对于特定的 bool 变量它不起作用:
class Player(object):
eaten = False
def __init__(self):
.....
def eat(Player):
Player.eaten = True
问题是,当函数被调用时,eaten 没有覆盖类中的变量。对于其他变量,它可以正确执行我想要的操作。
编辑:
如果在类播放器的方法内,我在调用 eat()
之后添加 print(self.eaten)
,它仍然始终打印 False
class Player(object):
eaten = False
def move():
print(self.eaten)
def eat(Player):
Player.eaten = True
谢谢!
最佳答案
eaten
应该是一个实例变量,而不是一个类变量 - 你可以让一些玩家被吃掉而其他人没有,并且将它作为一个类变量意味着它会影响所有玩家,这可能不是你想要什么。
class Player(object):
def __init__(self):
self.eaten = False
def move(self):
if self.eaten:
print("I have eaten so I can move")
else:
print("I can't move! I'm hungry!")
def eat(player, food):
player.eaten = True # change `eaten` for the player
# passed as parameter!
>>> p = Player() # creates a instance of the Player class
>>> q = Player() # creates another instance of the Player class
>>> eat(p, 'apple') # player `p` eates apple
>>> p.move()
I have eaten so I can move
>>> q.move()
I can't move! I'm hungry!
print(p.eaten) # will print True
print(q.eaten) # will print False
关于python - 从 Python 中的函数访问类变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51423959/