为什么 getattr 不能用于内置属性?
why won't getattr work for built in attributes?
下面的代码应该打印 "person is true"
和 "plant is true"
,但它只打印第一个。我已经对其进行了测试,出于某种原因,我的代码仅适用于事后设置的属性,而不适用于构造函数中始终为真或假的属性。我做错了什么?
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, )
您在 __init__
方法中编写了 plant = True
,使其成为局部变量而不是属性。
改为:
def __init__(self,person):
self.entity = self
self.person = person
self.plant = True
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.
下面的代码应该打印 "person is true"
和 "plant is true"
,但它只打印第一个。我已经对其进行了测试,出于某种原因,我的代码仅适用于事后设置的属性,而不适用于构造函数中始终为真或假的属性。我做错了什么?
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, )
您在 __init__
方法中编写了 plant = True
,使其成为局部变量而不是属性。
改为:
def __init__(self,person):
self.entity = self
self.person = person
self.plant = True
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.