0
点赞
收藏
分享

微信扫一扫

python中__init__、__getattr__、__setattr__、__call__的使用


class A():
    '''
    __init__、__getattr__、__setattr__、__call__、、都是内置函数
    在某些时候回自动被调用
    对象的属性储存在对象的__dict__属性中,__dict__为一个词典,对应在java中使用反射获取所有属性
    可使用obj.__dict__['a'] = 3修改属性
    '''
    #初始化时自动调用
    def __init__(self,ax,bx):
        self.a = ax
        self.b = bx
    def f(self):
        print (self.__dict__)
    #访问类中不存在的成员时会自动调用
    def __getattr__(self,name):
        print ("__getattr__")
    #点赋值运算“.”时自动被调用
    def __setattr__(self,name,value):
        print ("__setattr__")
        self.__dict__[name] = value
    #“()”运算时调用回调方法,可将对象当函数使用
    def __call__ (self, key):
        return key

a = A(1,2)
a.f()
a.x
a.x = 3
a.f()
a(5)



举报

相关推荐

0 条评论