栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

【python机制 - 04】

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【python机制 - 04】

__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'

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/350863.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号