112. python高级------闭包与装饰器(7)
python修炼第二十六天
2019年 4月 26日 晴
1.类方法
class My(object):
def __init__(self):
print('初始化')
self.age = 100
# 实例方法
def get_age(self):
return self.age
# 类方法
@classmethod
def get_name(cls):
return "zhangsan"
# 实例对象()
def __call__(self, *args, **kwargs):
print("call")
@classmethod
def set_value(cls,value):
cls.value = value
# my = My()
# print(my.get_age())
# print(My.get_name())
# print(My.get_age())
my = My()
my() # 实例对象()
初始化
call
2.类装饰器
class MyFun(object):
def __init__(self, func):
self.func = func
print(self.func)
def __call__(self, *args, **kwargs):
print("call")
# 原先函数调用
return self.func(*args, **kwargs)
@MyFun # test = MyFun(test)
def test(args):
print("test", args)
test(123)
<function test at 0x000001EF7BBC2EA0>
call
test 123
3.类装饰器传参
class MyFun(object):
def __init__(self, func):
self.func = func
print(self.func)
def __call__(self, *args, **kwargs):
print("call")
# 原先函数调用
return self.func(*args, **kwargs)
@classmethod
def set_value(cls, value):
print(value)
return cls
# return MyFun
# 分成两步
# 1.当成类调用类方法传参,返回一个类名
# 2.@类名===> test = 类(test)
@MyFun.set_value("123")
def test(args):
print("test", args)
test(123)
123
<function test at 0x0000013543522EA0>
call
test 123