python,__getattr__与__getarribute__特殊方法

__getattribute__对应的是 . 运算符,解释器会首先调用该方法,如果找不到指定的属性,则会调用__getattr__方法。

class Test1:
	def normal(self):
		print("this is normal")

class Test2:
	def __getattribute__(self, other):
		print("getattribute")

class Test3:
	def __getattr__(self, other):
		print("getattr")

class Sample1(Test1, Test2, Test3):
	pass
	
>>> s1 = Sample1()
>>> s1.normal
>>> getattribute
>>> s1.normal()
>>> Traceback (most recent call last):
  File "test.py", line 17, in <module>
    s1.normal()
TypeError: 'NoneType' object is not callable

"""
上例说明,python解释器会调用__getattribute__来处理 . 属性调用
"""


class Sample2(Test1, Test3):
	pass

>>> s2 = Sample()
>>> s2.normal()
>>> this is normal
>>> s2.bad
>>> getattr

"""
上例说明,当自带的__attribute__方法找不到指定参数时,会调用__getattr__方法
"""

在源文件中导入的module也是Module对象,它和其它对象一样,都遵从这种属性调用机制,所以可以在源文件中定义__getattr__方法,这样当它作为模块被导入时,如果有不属于本模块的属性被调用,则可以在__attr__方法中动态的调用其它模块中的属性予以返回。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

HilariousDog

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值