加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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.因为,当您向类添加值时,所有实例都将共享数据.

您可以使用这样的__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

引用__getattr__文档,

Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for self). name is the attribute name.

注意:__getattr__超过__getattribute__的优点是,始终会调用__getattribute__,即使当前对象具有该属性,我们也必须手动处理.但是,如果在层次结构中找到属性,则不会调用__getattr__.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读