用描述符自定制静态属性property,静态方法staticmethod,类方法classmethod

一.自定制静态属性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()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值