我在子类方面遇到问题。我们的任务是尽可能多地使用继承。现在我收到了这个错误,显然我一定做错了什么。
如果我想从子类调用 self.__symbol
会发生什么?我正在生成 20 个 Plant
对象,然后每个对象都会生成一个后代。
真正让我困惑的是,它一定在某个时刻存在,因为经过我的 #temporary
修复测试,__repr__
工作得很好。如何让它保持可调用状态,而无需在子组件的 __init__ 中重新定义它 - 因为这会违背继承的目的,不是吗?我使用 super().performAction()
或 super().__init__
扩展的方式可能有问题吗?所有教程都建议采用这种方法。
class Thing:
""" Represents all possible creatures in the world.
"""
def __init__(self, symbol, x, y):
"""
"""
self.__symbol = symbol
self.__position = (x,y)
self.__age = 0
def __repr__(self):
return (self.__symbol)
#print ('debug: i am', self, '. I´m at', self.__position)
def performAction(self, world):
self.__age += 1
pass
class Plant(Thing):
""" Represents all possible plants in the world.
"""
def __init__(self, symbol, x, y):
super().__init__(symbol, x, y)
self.__seedCycle = 6
def performAction(self, world):
super().performAction(world)
self.__seedCycle -=1
if self.__seedCycle <= 0:
randomdirection = [(0,1),(0,-1),(1,0),(-1,0)]
random.shuffle(randomdirection)
for i in randomdirection:
x = world.getPos(self)[0] + i[0]
y = world.getPos(self)[1] + i[1]
if world.getObject(x, y) == '.':
world.spawn(self.__symbol, x, y)
# temporary fix: world.spawn(str(self), x, y)
break
最佳答案
带有前导双下划线的属性意味着“私有(private)”,并且不能从其他类访问。
Python 通过在访问属性时将类名放在属性前面来实现此目的。这就是您在错误消息中看到 _Plant__symbol
的原因。
最简单的解决方案是将 __symbol
重命名为不带两个前导下划线的名称,以便可以从其他类访问它。
str() 方法在这里起作用,因为它调用 Test 对象的 __repr__
方法,并且 Test 对象可以访问它自己的“私有(private)”属性。
关于python - 属性错误: 'Corn' object has no attribute '_Plant__symbol' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34257190/