python - 从 Python 中的函数访问类变量

标签 python oop

我正在使用 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/

相关文章:

C++ 覆盖继承的方法

php - 如何在用户点击提交按钮时将数据发送回相同的表单

python - 使用 Pygments 检测代码片段的编程语言

php - 我可以从 PHP 中的父类(super class)构造函数将对象分配给子类吗?

python - 无法在 aws CDK 中找到 select_subnets 函数

python - 如果我在长度为 1 的 QuerySet 上使用 first() 与 last(),为什么会得到不同的结果

python - 将子文件夹内容移动到python中的父文件夹

python - 如何在 Python 中的图像上打印印地语句子(unicode)?

python - OpenCV:如何用鼠标连续绘制?

Python 结构问题 : Giving an 'engine' class to everything