如何访问Python中继承类使用的类变量?

时间:2014-03-23 04:08:46

标签: python inheritance

我有一个主要的播放器类,它由两个子类bot1和bot2继承。在播放器类中,我想要一个变量来跟踪机器人子类最后采取的操作。

class player:

    def printstuff(self):
        print self.lastplay.name(self)

    def __init__(self, name):
        self._name = name
        self.lastplay = 0

p1 = player.StupidBot("sb") #both of these modify lastplay class variable
p2 = player.RandomBot("rb")
print player.printstuff() #throws error

当我运行时,我收到以下错误。

AttributeError: 'module' object has no attribute 'printshit'

1 个答案:

答案 0 :(得分:1)

p1 = player.StupidBot("sb") #both of these modify lastplay class variable
p2 = player.RandomBot("rb")
print player.printstuff() #throws error

printstuff是继承类的属性:

print p1.printstuff(), p2.printstuff()