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.pyclassTest(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')"""实现链式操作"""classTest2(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