以下代码应打印"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, )
答案 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.