'''高阶函数启蒙'''
'''
1、__str__
功能:如果定义了该函数,当print当前实例化对象的时候,会返回该函数的return信息
用法:
def __str__(self):
retuen str_type
参数:
无
返回值:
一般返回对于该类的描述信息
示例:
class Test(object):
def __str__(self):
return '这是关于这个类的描述'
test = Test()
print(test)
2、__getattr__
功能:
当调用的属性或者方法不存在时,会返回该方法定义的信息
用法:
def __getattr__(self,key):
print(something……)
参数:
key:调用任意不存在的属性名
返回值:
可以是任意类型也可以不进行返回
示例:
class Test():
def __getattr__(self,key):
print('这个key:{}不存在'.format(key))
test = Test()
test.a
3、__setattr__
功能:
拦截当前类中不存在的属性与值,可以做一些业务处理
用法:
def __setattr__(self,key,value):
self.__dict__[key] = value
参数:
key 当前的属性名
value 当前的参数对应的值
返回值:
无
示例:
class Test(object):
def __setattr__(self,key,value):
if key not in self.__dict__:
self.__dict__[key] = value
t = Test()
t.name = 'dewei'
t.name
4、__call__
用法:
def __call__(self,*args,**kwargs):
print('call will start')
参数:
可传任意参数
返回值:
与函数情况相同可有可无
示例:
class Test(object):
def __call__(self,**kwargs):
print('args is {}'.format(kwargs))
t = Test()
t(name='dewei')
'''
class Test(object):
def __str__(self):
return 'this is a test class'
def __getattr__(self, item):
print('这个key:{} 并不存在'.format(item))
def __setattr__(self, key, value):
if key not in self.__dict__:
self.__dict__[key] = value
print(self.__dict__)
print(key, value)
def __call__(self,a):
print('call 函数')
print(a)
t = Test()
print(t)
t.a
print('#'*60)
t.name = 'Tom'
print('#'*60)
t('Tom')
print('--'*80)
class Test2(object):
def __init__(self,attr=''):
self.__attr = attr
def __call__(self,name):
return name
def __getattr__(self, key):
if self.__attr:
key = '{}.{}'.format(self.__attr,key)
else:
key = key
print(key)
return Test2(key)
t2 = Test2()
name = t2.a.b.c('dewei')
print(name)
result = t2.name.age.sex('ok')
print(result)