__str__
函數(shù)
def __str__(self): return str_type
__getattr__
函數(shù)
def __getattr__(self, key): print(something.….)
key: 調(diào)用任意不存在的屬性名
可以是任意類(lèi)型也可以不進(jìn)行返回
__setattr__
函數(shù)
def __settattr__(self, key,value): self._dict_[key] = value
key當(dāng)前的屬性名
value 當(dāng)前的參數(shù)對(duì)應(yīng)的值
__call__
函數(shù)
def __call__(self,*args,**kwargs): print( 'call will start')
實(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ì)直接打印出來(lái),而不是報(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類(lèi)的高級(jí)函數(shù)的文章就介紹到這了,更多相關(guān)Python高級(jí)函數(shù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
標(biāo)簽:寧夏 大同 盤(pán)錦 林芝 漯河 普洱 南平 海南
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Python類(lèi)的高級(jí)函數(shù)詳解》,本文關(guān)鍵詞 Python,類(lèi),的,高級(jí),函數(shù),詳解,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。