Python类的高级函数详解
Python类的高级函数详解,博智网带你了解详细信息 。
__str__函数
- 如果定义了该函数 , 当print当前实例化对象的时候 , 会返回该函数的return信息
- 可用于定义当前类的描述信息
- 用法:
- 参数:无
- 返回值:一般返回对于该类的描述信息





实战
#!/usr/bin/python3# -*- coding: utf-8 -*-# @Time: 2021/8/15 18:22# @Author: InsaneLoafer# @File: object_func.pyclass 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] = valueprint(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 = attrdef __call__(self, name):print('key is {}'.format(self.__attr))return namedef __getattr__(self, key):if self.__attr:key = '{}.{}'.format(self.__attr, key)else:key = keyprint(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'}aa.ckey is a.cinsaneProcess finished with exit code 0
到此这篇关于Python类的高级函数的文章就介绍到这了,更多相关Python高级函数内容请搜索趣讯吧以前的文章或继续浏览下面的相关文章希望大家以后多多支持趣讯吧!
推荐阅读
- 河蚌体内珍珠的形成过程是
- 12w灯泡一小时耗电量
- 10h是什么意思
- 猫屎咖啡是真的猫屎吗
- 牛肉是属于发的东西吗
- 辣椒酱的制作方法及配料
- 监控不显示画面怎么办
- 13妖什么牌
- 苹果x手机电池容量是多少
- x和xs外观区别是什么
