Python类的高级函数详解
作者:Insane_Loafer 时间:2022-11-21 04:59:18
__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
来源:https://blog.csdn.net/m0_48978908/article/details/119717505
标签:Python,类,高级函数
0
投稿
猜你喜欢
Python3安装Pillow与PIL的方法
2022-09-27 10:21:28
轻轻松松学习JavaScript
2024-06-07 15:51:08
详解javascript中的变量提升和函数提升
2024-06-07 15:53:28
Python实现信息轰炸工具(再也不怕说不过别人了)
2021-10-05 17:01:08
python爬虫-模拟微博登录功能
2021-12-13 21:54:08
MySQL数据库完全卸载的方法
2024-01-28 05:59:21
python画图把时间作为横坐标的方法
2021-06-17 08:13:28
Python使用背景差分器实现运动物体检测
2023-06-21 09:37:22
基于python分析你的上网行为 看看你平时上网都在干嘛
2021-09-02 15:04:39
python pandas.DataFrame.loc函数使用详解
2023-10-04 07:01:58
php关于array_multisort多维数组排序的使用说明
2023-09-07 08:13:27
Django学习教程之静态文件的调用详解
2022-01-03 00:19:45
工作需要写的一个js拖拽组件
2024-04-08 10:53:20
改变链接,让别人永远找不到你的程序
2008-09-13 18:57:00
Python对列表的操作知识点详解
2022-05-08 09:06:39
深入分析Python中Lambda函数的用法
2023-07-01 16:03:21
MySql COALESCE函数使用方法代码案例
2024-01-14 03:47:25
Python3 字典dictionary入门基础附实例
2023-03-08 18:57:49
基于Python和openCV实现图像的全景拼接详细步骤
2023-05-30 17:35:07
使用Python实现二分法查找的示例
2022-02-08 13:52:53