Python @classmethod和 @staticmethod装饰器使用介绍

入坑Python近两年了,装饰器却几乎从未用到,也一直都是一知半解。这次有机会从类的两个装饰器入手,开始尝试去了解Python装饰器的使用方法。(希望这个博客能一直更新下去,多写点关于装饰器的内容)

上述两个装饰器实际应用很简单,都是在类中定义函数时采用的。

如果在定义一个函数时没有用到任何类和实例的属性、变量,那么在定义该函数前添加@staticmethod就可以定义静态函数。

如果在定义一个函数时只用到了类属性但没有用到实例属性、变量,那么添加@classmethod就可以定义类函数。

关于这两个装饰器的用法看下方这个代码就可以了:

class test():
    #不需要实例的类属性在这里定义
    my_name = "yuyu"
    def __init__(self,test_time):
        # 这里定义的是实例属性
        self.test_time = test_time
    
    @staticmethod
    def explain():
        print("This is a test class.")

    @classmethod
    def class_func(cls):
        print("My name is always ",cls.my_name)
    
    def instance_func(self):
        print("The test time is uncertain, now is ",self.test_time)


print("---If you create an instance, you can use the instance.---")
t_inst = test(12)
t_inst.explain()
t_inst.class_func()
t_inst.instance_func()

print("---If not, you can use the class without instance to call the stastic_fun and class_func---")
test.explain()
test.class_func()

(###目前的疑问###,如何同时在一个函数中调用类属性和实例属性?目前尝试在类函数中或者实例函数中都不可以实现。)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值