【python基础 - 04】__getattr__

__getattr__方法常用于以属性的方式调用类中的属性或方法,如MyClass.my_func().

定义Test类如下:

class Test(object):
    def _my_default(self, *args):
        print(f'func input {args}')

    def __getattr__(self, key):
        print(f'{key} not defined in Test')
        return self._my_default

执行

x = Test()
x.test_func('test getattr')

输出

test_func not defined in Test
func input ('test getattr',)

由此可以看出采用.的形式去调用属性、方法时就是在调用__getattr__,我们还可以使用该特性实现以属性的方式去调用dict中的元素,示例如下:

class Dict2Attr(object):
    def __init__(self, m_dict):
        self.m_dict = m_dict

    def __getattr__(self, key):
        return self.m_dict[key]


m_dict = dict(
    item1='value1',
    item2='value2',
)
m_attr_dict = Dict2Attr(m_dict)

# 以下每两行都是等价的
print(m_dict['item1'])
print(m_attr_dict.item1)

print(m_dict['item2'])
print(m_attr_dict.item2)

print(m_dict['item3'])
print(m_attr_dict.item3)  # 执行结果同上

输出

value1
value1
value2
value2
Traceback (most recent call last):
  File "xxx", line 22, in 
    print(m_dict['item3'])
KeyError: 'item3'

博主会持续更新一些人工智能领域的知识和实践、工作中遇到的问题和感悟、高效工作的方法和技巧,如果喜欢请关注、点赞、收藏支持

你可能感兴趣的:(python,python,r语言,开发语言)