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

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

__setattr__
函數(shù)
def __settattr__(self, key,value):
self._dict_[key] = value
key當前的屬性名
value 當前的參數(shù)對應的值

__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
到此這篇關于Python類的高級函數(shù)的文章就介紹到這了,更多相關Python高級函數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- python 類相關概念理解
- Python入門變量的定義及類型理解
- python學習之新式類和舊式類講解
- python入門課程第四講之內(nèi)置數(shù)據(jù)類型有哪些
- Python的內(nèi)置數(shù)據(jù)類型中的數(shù)字
- 一篇文章帶你了解Python中的類