Skip to main content
 首页 » 编程设计

python之属性错误 : 'Corn' object has no attribute '_Plant__symbol'

2024年10月24日9langtianya

我在处理子类时遇到问题。我们的任务是尽可能多地使用继承。现在我收到了这个错误,显然我一定是做错了什么。

如果我想从子类中调用它,self.__symbol 会怎样?我正在生成 20 个 Plant 对象,然后每个对象都用于生成一个后代。

真正让我感到困惑的是,它一定是在某个时候存在的,因为 __repr__ 在我的 #temporary 修复测试中工作正常。我如何才能让它保持可调用状态,而不仅仅是在子程序的 __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)”属性。