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

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

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

__call__函數(shù)
- 本質(zhì)是將一個類變成一個函數(shù)
- 用法:
def __call__(self,*args,**kwargs): print( 'call will start')
- 參數(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 '這個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')
"""實現(xià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
這個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類的高級函數(shù)的文章就介紹到這了,更多相關(guān)Python高級函數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python裝飾器實現(xiàn)函數(shù)運行時間的計算
這篇文章主要為大家詳細介紹了Python函數(shù)運行時間的計算,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2022-02-02
用Python計算三角函數(shù)之a(chǎn)tan()方法的使用
這篇文章主要介紹了用Python計算三角函數(shù)之a(chǎn)tan()方法的使用,是Python入門的基礎(chǔ)知識,需要的朋友可以參考下2015-05-05
Python 如何手動編寫一個自己的LRU緩存裝飾器的方法實現(xiàn)
本文主要介紹了Python如何手動編寫一個自己的LRU緩存裝飾器,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-12-12
使用Python實現(xiàn)查找PDF中的指定文本并高亮顯示
在處理大量PDF文檔時,有時我們需要快速找到特定的文本信息,本文將提供三個Python示例來幫助你在PDF文件中快速查找并高亮指定的文本,希望對大家有所幫助2024-03-03

