本篇文章小编给大家分享一下Python类的高级函数代码示例解析,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。
__str__函数
如果定义了该函数,当print当前实例化对象的时候,会返回该函数的return信息
可用于定义当前类的描述信息
用法:
def __str__(self): return str_type
参数:无
返回值:一般返回对于该类的描述信息
__getattr__函数
当调用的属性或者方法不存在时,会返回该方法定义的信息
用法:
def __getattr__(self, key): print(something.….)
参数:
key: 调用任意不存在的属性名
返回值:
可以是任意类型也可以不进行返回
__setattr__函数
拦截当前类中不存在的属性与值
用法:
def __settattr__(self, key,value): self._dict_[key] = value
参数:
key当前的属性名
value 当前的参数对应的值
返回值: 无
__call__函数
本质是将一个类变成一个函数
用法:
def __call__(self,*args,**kwargs): print( 'call will start')
参数: 可传任意参数
返回值: 与函数情况相同可有可无
实战
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2021/8/15 18:22 # @Author : InsaneLoafer # @File : object_func.py class Test(object): def __str__(self): return 'this is a test class' def __getattr__(self, key): return '这个key:{}并不存在'.format(key) def __setattr__(self, key, value): print(key, value) self.__dict__[key] = value print(self.__dict__) def __call__(self, *args, **kwargs): print('call will start') print(args, kwargs) t = Test() print(t) print(t.a) # 不存在的对象会直接打印出来,而不是报错 t.name = 'insane' t(123, name='loafer') """实现链式操作""" class Test2(object): def __init__(self, attr=''): self.__attr = attr def __call__(self, name): print('key is {}'.format(self.__attr)) return name def __getattr__(self, key): if self.__attr: key = '{}.{}'.format(self.__attr, key) else: key = key print(key) return Test2(key) # 递归操作 t2 = Test2() print(t2.a.c('insane'))
this is a test class 这个key:a并不存在 name insane {'name': 'insane'} call will start (123,) {'name': 'loafer'} a a.c key is a.c insane Process finished with exit code 0
茶杯头甜蜜终章dlc 官方手机版v1.0.0.3
下载火柴人传说暗影格斗内置菜单 最新版v3.0.1
下载荒野乱斗测试服 安卓版v61.10.3
下载荒野乱斗彩虹服 安卓版v61.10.3
下载寒霜启示录 安卓版v1.25.10
寒霜启示录是一款生存模拟游戏,不少玩家可能对于末日都有着自己
末日城堡免广告版 安卓最新版v0.7.1
末日城堡免广告版是一款非常好玩的模拟经营类游戏,内部可以不看
甜蜜人生模拟器 最新版v1.4.5
甜蜜人生模拟器是一款非常好玩的模拟恋爱手游,玩家在这里能够对
武器锻造师内置功能菜单 v10.4
武器锻造师内置菜单版是游戏的破解版本,在该版本中为玩家提供了
开放空间overfield 安卓版v1.0.5
开放空间Overfield是一款箱庭养成经营手游,让你在广阔