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).