目錄
__str____getattr____setattr____call__
__str__函式
- 如果定義了該函式,當print當前實體化物件的時候,會回傳該函式的return資訊
- 可用于定義當前類的描述資訊
- 用法:
def __str__(self):
return str_type
- 引數:無
- 回傳值:一般回傳對于該類的描述資訊

__getattr__函式
- 當呼叫的屬性或者方法不存在時,會回傳該方法定義的資訊
- 用法:
def __getattr__(self, key):
print(something.….)
- 引數:
- key: 呼叫任意不存在的屬性名
- 回傳值:
- 可以是任意型別也可以不進行回傳

- 可以是任意型別也可以不進行回傳
__setattr__函式
- 攔截當前類中不存在的屬性與值
- 用法:
def __settattr__(self, key,value):
self._dict_[key] = value
- 引數:
- key當前的屬性名
- value 當前的引數對應的值
- 回傳值: 無

__call__函式
- 本質是將一個類變成一個函式
- 用法:
def __call__(self,*args,**kwargs):
print( 'call will start’)
- 引數: 可傳任意引數
- 回傳值: 與函式情況相同可有可無

實戰
#!/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')
"""實作鏈式操作"""
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/294478.html
標籤:python
上一篇:c重戰——第十二站(函式下篇)
