一.自定制静态属性property
class Lazyproperty:
def __init__(self, func):
self.func = func
def __get__(self, instance, owner):
print("get")
if instance is None:
return self
res=self.func(instance)
instance.__dict__[self.func.__name__]=res
return res
class Foo:
@Lazyproperty
def jing(self):
return ("haha")
f1 = Foo()
print(f1.jing)
print(f1.jing)
print(f1.jing)
""""
Lazyproperty既是装饰器也是描述符
装饰器可以是函数,也可以是类,重点在于语法糖实现的内容意义
"""
二.静态方法staticmethod
class Lazy_staticmethod:
def __init__(self, func):
self.func = func
def __get__(self, instance, owner):
print("get")
def wapper(*args):
self.func(*args)
return wapper
class fff:
@Lazy_staticmethod
def foo(name):
print("%s叫了啊啊啊啊" % name)
@staticmethod
def eoo(name):
print("%s叫了呀呀呀呀" % name)
aa = fff()
aa.eoo("lily")
fff.eoo("nary")
aa.foo("haly")
fff.foo("linda")
三.类方法classmethod
class Lazy_classmethod:
def __init__(self,func):
self.func=func
def __get__(self, instance, owner):
print("get")
def wrapper():
if instance is None:
self.func(owner)
else:
self.func(instance)
return wrapper
class Foo:
tag=1
@Lazy_classmethod
def cvvvv(cls):
print("%s叫了喵猫喵"%cls.tag)
@classmethod
def bvvv(cls):
print("%s叫了汪汪汪"%cls.tag)
f1=Foo()
f1.cvvvv()
Foo.cvvvv()