Python 官方文档:入门教程 => 点击学习
__str__函数 如果定义了该函数,当print当前实例化对象的时候,会返回该函数的return信息 可用于定义当前类的描述信息 用法: def _
__str__
函数
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
到此这篇关于python类的高级函数的文章就介绍到这了,更多相关Python高级函数内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: Python类的高级函数详解
本文链接: https://www.lsjlt.com/news/132891.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0