您当前的位置:首页 > IT编程 > python
| C语言 | Java | VB | VC | python | Android | TensorFlow | C++ | oracle | 学术与代码 | cnn卷积神经网络 | gnn | 图像修复 | Keras | 数据集 | Neo4j | 自然语言处理 | 深度学习 | 医学CAD | 医学影像 | 超参数 | pointnet | pytorch | 异常检测 | Transformers | 情感分类 | 知识图谱 |

自学教程:Python类的高级函数详解

51自学网 2021-10-30 22:20:49
  python
这篇教程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.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] = 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'}aa.ckey is a.cinsaneProcess finished with exit code 0

到此这篇关于Python类的高级函数的文章就介绍到这了,更多相关Python高级函数内容请搜索51zixue.net以前的文章或继续浏览下面的相关文章希望大家以后多多支持51zixue.net!


python列表与列表算法详解(2)
利用Python+Selenium破解春秋航空网滑块验证码的实战过程
万事OK自学网:51自学网_软件自学网_CAD自学网自学excel、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。