抱歉,问题可能很小白,但是实在不明白,求助下。网上看了好几个例子,都看不懂
class Person:
def __init__(self):
print "init"
@staticmethod
def sayHello(hello):
if not hello:
hello='hello'
print "i will sya %s" %hello
@classmethod
def introduce(cls,hello):
cls.sayHello(hello)
print "from introduce method"
def hello(self,hello):
self.sayHello(hello)
print "from hello method"
我的理解是加了@staticmethod之后,直接可以Person.sayHello("mimi")就出效果了,而不用p=Person()去创建实例。可这样有什么用呢。具体什么时候需要这样呢。
@classmethod,需要传入第一个参数是本class,也是不用创建instance就可以用。可这样有什么用呢。具体什么时候需要这样呢。
实在不明白~~~希望有大神来解答下。
staticmethod并不是因为不想创建实例才声明的,而是声明该方法不会更改实例本身的数据。
classmethod也并不是因为不想创建实例才声明的,而是为了实现对类本身的操作(传入cls之后就可以对自身的属性和方法进行操作)。
仅仅是个人浅薄的见解,供题主参考一下。