類方法和靜態方法
普通函數
class Person:
def normal_method():
print('normal')
Person.normal_method()
# Person().normal_method()
print(Person.__dict__)
- Person.normal_method()可以,是因為這個方法只是被Person這個名詞空間管理的一個普通方法而已,normal_method()只是Person的一個屬性而已
- Person().normal_method()不可以,由于normal_method()在定義的時候沒有指定self,所以不能完成實例對象的綁定,所以不能用
- 雖然語法是對的,但是禁止這么寫
實例方法
class Person:
def method(self):
return("{}'s method".format(self))
tom = Person()
print(tom.method())
類方法
class Person:
@classmethod
def class_method(cls):
print('class = {0.__name__} ({0})'.format(cls))
cls.HEIGHT = 179
Person.class_method()
print(Person.__dict__)
- 在類定義中,使用@classmethod裝飾器修飾的方法
- 必須至少有一個參數,且第一個參數留給cls,cls指代調用者即類對象自身
- 不要修改cls標識符
- 通過cls可以直接操作類的屬性
- python的類方法,類似于C++、Java中的靜態方法
靜態方法
class Person:
@classmethod
def class_method(cls):
print('class = {0.__name__} ({0})'.format(cls))
cls.HEIGHT = 179
@staticmethod
def static_method():
print(Person.HEIGHT)
Person.class_method()
Person.static_method()
print(Person.__dict__)
- 在類定義中,使用@staticmethod裝飾器修飾的方法
- 調用時,不會隱式地傳入參數
- 靜態方法,只是表明這個方法屬于這個名詞空間
方法的調用
class Person:
def normal_method():
return('normal')
def method(self):
return("{}'s method".format(self))
@classmethod
def class_method(cls):
cls.HEIGHT = 179
return ('class = {0.__name__} ({0})'.format(cls))
@staticmethod
def static_method():
return (Person.HEIGHT)
print('----類訪問-----')
print(1, Person.normal_method())
# print(2, Person.method()) # 報錯,因為沒有實例化,缺少一個參數,給一個參數就行
print(3, Person.class_method())
print(4, Person.static_method())
print(Person.__dict__, end='\n\n')
print('------實例訪問-------')
print('----tom----')
tom = Person()
# print(1,tom.normal_method()) # 報錯,多給了self參數
print(2, tom.method())
print(3, tom.class_method())
print(4, tom.static_method(), end='\n\n')
print('----jerry----')
jerry = Person()
# print(1, jerry.normal_method())
print(2, jerry.method())
print(3, jerry.class_method())
print(4, jerry.static_method())
總結
- 類除了實例方法,都可以調用,實例方法需要對象的實例作為第一參數
- 實例除了普通方法,都可以調用,調用實例方法傳入實例自身,靜態方法和類方法需要傳入實例的類
本文來自投稿,不代表Linux運維部落立場,如若轉載,請注明出處:http://www.www58058.com/88299