一.自定制靜态屬性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 #setattr(instance,self.func.__name__,res)
return res
# def __set__(self, instance, value):
# pass
class Foo:
@Lazyproperty # jing=Lazyproperty(jing) 既是類裝飾器産生對象,又是描述符代理jing屬性
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)
# print(self)
# print(instance)
return wapper
class fff:
@Lazy_staticmethod # foo=Lazy_staticmethod(foo)
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)
# print(self)
# print(instance)
# print(owner)
return wrapper
class Foo:
tag=1
@Lazy_classmethod #cvvvv=Lazy_classmethod(cvvvv)
def cvvvv(cls):
print("%s叫了喵貓喵"%cls.tag)
@classmethod
def bvvv(cls):
print("%s叫了汪汪汪"%cls.tag)
f1=Foo()
# f1.bvvv()
# Foo.bvvv()
f1.cvvvv()
Foo.cvvvv()