首页 > 编程语言 > 详细

python __getattr__, __setattr__

时间:2019-12-27 18:04:30      阅读:96      评论:0      收藏:0      [点我收藏+]

调用类中原本没有定义的属性时候,调用__getattr__

class Cat(object):
    def __init__(self):
        self.name = "jn"

    def __getattr__(self, item):
        return "tm"


cat = Cat()
print(cat.name)
print(getattr(cat, ‘name‘))
print("*" * 20)
print(cat.age)
print(getattr(cat, ‘age‘))

#对实例的属性进行赋值的时候调用__setattr__

class Dict(dict):

    def __getattr__(self, key):
        try:
            return self[key]
        except KeyError:
            raise AttributeError(r"‘Dict‘ object has no attribute ‘%s‘" % key)

    def __setattr__(self, key, value):
        self[key] = value

d = Dict(a=1, b=2)
print (d[‘a‘])
print (d.a) 
d.a = 100 
print (d[‘a‘])

 

python __getattr__, __setattr__

原文:https://www.cnblogs.com/honglingjin/p/12108722.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!