python __getattr__ __getattribute__

本文介绍了Python中用于对象属性访问的`setattr`、`getattr`函数,以及`__getattr__`和`__getattribute__`特殊方法。`setattr`用于设置对象属性,如`setattr(Test, 'x', 1)`;`getattr`用于获取对象属性,但不会触发`__getattribute__`。`__getattr__`仅在实例尝试访问不存在的属性时调用,需注意避免无限递归;而`__getattribute__`在每次访问属性时都会被调用,包括方法调用。直接赋值如`test.x = 1`会调用`__setattr__`,若属性未定义`__getattribute__`,则会尝试`__getattr__`。" 110399170,10293153,Python模拟JS请求:解决腾讯微博OAuthVerifier获取问题,"['Python编程', '网络请求', 'API接口', '腾讯微博开发']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

setattr(x,y,z)   ----> x.y=z

setattr(Test,'x'.1)    Test 为类对象

getattr(object,name[,default])

getattr(x,'y')   -----> x.y

不会触发__getattribute__ 

 

__getattr__:

如果实例instance通过instance.name访问属性name,

如果类中没有定义name,会触发此方法,

类中定义了name 这个属性,不会触发此方法

注意:如果在__getattr__(self, attr)存在通过self.attr访问属性,会出现无限递归错误。

 

__getattribute__

如果实例instance通过instance.name访问属性name,

不管类中有没有定义name 属性,都会触发此方法,

 

注意:如果在__getattribute__(self, attr)方法下存在通过self.attr访问属性,会出现无限递归错误

如果类中定义了__getattr__方法,除非通过__getattribute__显式的调用它,或者__getattribute__方法出现AttributeError错误,否则__getattr__方法不会被调用

  • test.x =1 
  • print(test.x)      设置/访问属性 每次都会调用 __getattribute__方法

 

test.x =1  ---->调用__setattr__,不建议自己实现

print(test.x)  ====> 如果x属性没有设置__getattribute__会去调用 __getattr__方法

 

class Test1:
    def __init__(self):
        self.s = 2

    def __getattr__(self, key):
        print("__getattr___", key)
        if key == 'x':
            return 'default x'
        return key

 T = Test1()
    print(T.s) 
    #输出 
    # 2
    print(T.f)  #类没有f属性,就调用了__getattr__
    #输出
    #__getattr___ f
    #f
class Test3():
    def __init__(self):
        self.s = 2

    def __getattribute__(self, key):
        print('__getattribute__')
        if key == 'x':
            return 'default x'
        else:
            return key
----------------------
    T =Test3()  #不管类里有没有该属性 都调用了__getattribute__
    print(T.s)
    #输出:
    #__getattribute__
    #s
    print(T.x)
    # 输出
    # __getattribute__
    # default
    # x
class Test2:
    def __init__(self):
        self.s = 2

    def __getattribute__(self, key):
        print('__getattribute__')
        if key == 'x':
            pass
            # return 'default x'
        else:
            raise AttributeError

    def __getattr__(self, key):
        print("__getattr___", key)

        return key
--------------------------------
    T = Test2()
    #输出
    # print(T.x)
    #__getattribute__
    #None

    print(T.f) # __getattribute__ 抛出AttributeError,调用 __getattr___
    #输出
    # __getattribute__
    # __getattr___ f
    # f

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值