python – 当属性不存在时返回None
发布时间:2020-12-20 12:06:07 所属栏目:Python 来源:网络整理
导读:class test(object):def __init__(self,a = 0): test.a = at = test()print test.a ## obviously we get 0''' ====== Question ====== '''print test.somethingelse ## I want if attributes not exist,return None. How to do that? 解决方法 首先,您将该变
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? 解决方法
首先,您将该变量添加到类test.a = a中.您应该将它添加到实例中,self.a = a.因为,当您向类添加值时,所有实例都将共享数据.
您可以使用这样的 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 引用__getattr__文档,
注意:__getattr__超过 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |