入坑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()
(###目前的疑问###,如何同时在一个函数中调用类属性和实例属性?目前尝试在类函数中或者实例函数中都不可以实现。)