Mac*_*nhe 3 python oop attributes class python-2.7
class test(object):
def __init__(self, a = 0):
test.a = a
t = test()
print test.a ## obviously we get 0
''' ====== Question ====== '''
print test.somethingelse ## I want if attributes not exist, return None. How to do that?
Run Code Online (Sandbox Code Playgroud)
the*_*eye 10
首先,您要将变量添加到类中test.a = a.您应该将它添加到实例中self.a = a.因为,当您向类添加值时,所有实例都将共享数据.
你可以使用这样的__getattr__功能
class test(object):
def __init__(self, a = 0):
self.a = a
def __getattr__(self, item):
return None
t = test()
print t.a
print t.somethingelse
Run Code Online (Sandbox Code Playgroud)
引用__getattr__文档,
当属性查找未在通常位置找到属性时调用(即,它不是实例属性,也不是在类树中找到自己).name是属性名称.
注意:__getattr__ over 的优点__getattribute__是,__getattribute__即使当前对象具有该属性,我们也必须手动处理.但是,如果在层次结构中找到属性,__getattr__则不会调用它.