@staticmethod和@classmethod的區(qū)別
- class 類
- @staticmethod
- @classmethod
首先創(chuàng)建一個(gè)類,如果想要調(diào)用Student類中的方法get_score(),就需要先創(chuàng)建類的實(shí)例,然后再用類的對象再去調(diào)用方法
In [3]: class Student():
...: def __init__(self, name, score):
...: self.name = name
...: self.score = score
...: def get_score(self):
...: print('%s get %s ' % (self.name, self.score))
...:
...:
In [4]: student = Student('treehl', 100)
In [5]: student.get_score()
treehl get 100
@staticmethod和@classmethod一個(gè)是靜態(tài)方法,另一個(gè)是類的方法,兩個(gè)裝飾器的作用都可以使類不必再創(chuàng)建實(shí)例,直接用類來調(diào)用方法(類名.方法())
它們使用上的區(qū)別
- @staticmethod不需要傳遞self,也不需要cls參數(shù),就跟使用函數(shù)一樣(類名.方法()或類名.屬性名)
- @classmethod也不需要像實(shí)例方法一樣要傳遞self,但它需要cls參數(shù)(cls.類名()或cls.方法()或cls.屬性())
要理解這些,首先需要理解類屬性和實(shí)例屬性的區(qū)別
In [6]: class A():
...: bar = 1
...: def foo(self):
...: print 'foo'
...: @staticmethod
...: def static_foo():
...: print 'static_foo'
...: print A.bar
...: @classmethod
...: def class_foo(cls):
...: print 'class_foo'
...: print cls.bar
...: cls().foo()
...:
In [7]: A.static_foo()
static_foo
1
In [8]: A.class_foo()
class_foo
1
foo