为什么赢得内置属性的getattr工作?

时间:2015-03-26 19:07:36

标签: python oop getattr

以下代码应打印"person is true""plant is true",但它只打印第一个。我已经测试了它,并且由于某种原因,我的代码仅适用于事后设置的属性,而不是构造函数中始终为true或false的属性。我做错了什么?

class entity:
    def __init__(self,person):
        self.entity = self
        self.person = person
        plant = True

e = entity(True)
for attribute in dir(e):
    if getattr(e, attribute) is True:
        print '"%s" is True' % (attribute, )

2 个答案:

答案 0 :(得分:3)

您已在plant = True方法中编写__init__,这使其成为局部变量而非属性。

将其更改为:

def __init__(self,person):
    self.entity = self
    self.person = person
    self.plant = True

答案 1 :(得分:1)

class entity:
    def __init__(self,person):
        self.entity = self
        self.person = person
        plant = True #you're not editting the object, this is a local variable

要编辑entity的实例变量,您需要使用self.