class Test:
def __init__(self, id):
self.id = id
def printd(self):
print self.id
print('Arg in Method: ', self)
@staticmethod
def smethod(*arg):
print('Arg in staticMethod: ', arg)
@classmethod
def cmetod(*arg):
print("Arg in classMethod: ", arg)
#classmethod 是和一个class相关的方法,可以通过类或类实例调用,并将该class对象(不是class的实例对象)隐式地 当作第一个参数传入
#staticmethod 基本上和一个全局函数差不多,不会隐式地传入任何参数
test = Test(1)
test.printd()
test2 = Test(2)
test2.printd()
test.cmetod()
Test.cmetod()
Test.smethod()
test.smethod()输出:
1
('Arg in Method: ', <method.Test instance at 0x00000000028D9208>)
2
('Arg in Method: ', <method.Test instance at 0x00000000028E3388>)
('Arg in classMethod: ', (<class method.Test at 0x00000000028D44C8>,))
('Arg in classMethod: ', (<class method.Test at 0x00000000028D44C8>,))
('Arg in staticMethod: ', ())
('Arg in staticMethod: ', ())
结论:
@classmethod means: when this method is called, we pass the class as the first argument instead of the instance of that class (as we normally do with methods). This means you can use the class and its properties inside that method rather than a particular instance.@staticmethod means: when this method is called, we don't pass an instance of the class to it (as we normally do with methods). This means you can put a function inside a class but you can't access the instance of that class (this is useful when your method does not use the instance).
本文深入探讨了Python中的装饰器与类方法的区别,包括@classmethod与@staticmethod的作用及使用场景,通过实例展示了如何在类中正确应用这两种方法。
419

被折叠的 条评论
为什么被折叠?



