__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.….)
key: 調(diào)用任意不存在的屬性名
可以是任意類型也可以不進(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ù)
- 本質(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)文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- python 類相關(guān)概念理解
- Python入門變量的定義及類型理解
- python學(xué)習(xí)之新式類和舊式類講解
- python入門課程第四講之內(nèi)置數(shù)據(jù)類型有哪些
- Python的內(nèi)置數(shù)據(jù)類型中的數(shù)字
- 一篇文章帶你了解Python中的類