Python類的高級(jí)函數(shù)詳解
__str__函數(shù)
- 如果定義了該函數(shù),當(dāng)print當(dāng)前實(shí)例化對(duì)象的時(shí)候,會(huì)返回該函數(shù)的return信息
- 可用于定義當(dāng)前類的描述信息
- 用法:
def __str__(self): return str_type
- 參數(shù):無
- 返回值:一般返回對(duì)于該類的描述信息

__getattr__函數(shù)
- 當(dāng)調(diào)用的屬性或者方法不存在時(shí),會(huì)返回該方法定義的信息
- 用法:
def __getattr__(self, key): print(something.….)
- 參數(shù):
key: 調(diào)用任意不存在的屬性名
- 返回值:
可以是任意類型也可以不進(jìn)行返回

__setattr__函數(shù)
- 攔截當(dāng)前類中不存在的屬性與值
- 用法:
def __settattr__(self, key,value): self._dict_[key] = value
- 參數(shù):
key當(dāng)前的屬性名
value 當(dāng)前的參數(shù)對(duì)應(yīng)的值
- 返回值: 無

__call__函數(shù)
- 本質(zhì)是將一個(gè)類變成一個(gè)函數(shù)
- 用法:
def __call__(self,*args,**kwargs): print( 'call will start')
- 參數(shù): 可傳任意參數(shù)
- 返回值: 與函數(shù)情況相同可有可無

實(shí)戰(zhàn)
#!/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 '這個(gè)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) # 不存在的對(duì)象會(huì)直接打印出來,而不是報(bào)錯(cuò)
t.name = 'insane'
t(123, name='loafer')
"""實(shí)現(xiàn)鏈?zhǔn)讲僮?""
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
這個(gè)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
到此這篇關(guān)于Python類的高級(jí)函數(shù)的文章就介紹到這了,更多相關(guān)Python高級(jí)函數(shù)內(nèi)容請(qǐng)搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。
關(guān)注官方微信