Python類方法、靜態方法與例項方法
阿新 • • 發佈:2018-12-15
@classmethod類方法
除靜態方法與類方法外,類的其他方法都屬於例項方法。 類方法:
- 方法中的self是類本身
- 只能訪問類變數,不能訪問例項變數不能訪問例項變數
- 即可通過類呼叫也可以通過例項呼叫
>>> class person(): def __init__(self,name): self.name = name @classmethod def say(self): print('hi %s'%self.name) >>> a = person('a') >>> a.say() Traceback (most recent call last): File "<pyshell#36>", line 1, in <module> a.say() File "<pyshell#34>", line 6, in say print('hi %s'%self.name) AttributeError: type object 'person' has no attribute 'name'
只能訪問類變數self.n
>>> class person():
n = 'andy'
def __init__(self,name):
self.name = name
@classmethod
def say(self):
print('hi %s'%self.n)
>>> a = person('a')
>>> a.say()
hi andy
即可通過類呼叫也可以通過例項呼叫
>>> class person(): def __init__(self,name): self.name = name @classmethod def say(self,content): print('hi %s'%content) >>> person.say('a') #無需將類例項化,通過類直接呼叫 hi a >>> p=person('a') >>> p.say('bb') #通過例項直接呼叫 hi bb >>>
@staticmethod靜態方法
靜態方法是指類中無需例項參與即可呼叫的方法(不需要self引數),在呼叫過程中,無需將類例項化,直接在類之後使用.號運算子呼叫方法。 通常情況下,靜態方法使用@staticmethod裝飾器來宣告。 靜態方法:
-
不會隱式傳遞self
-
只是名義上歸類管理,實際上在靜態方法裡訪問不了類或例項中的任何屬性
-
即可通過類直接呼叫,不需要建立物件,也可以通過例項
>>> class person(): def __init__(self,name): self.name = name @staticmethod def say(): print('hi') >>> person.say() #無需將類例項化,通過類直接呼叫 hi >>> p=person('a') >>> p.say() #通過例項直接呼叫 hi >>>
這裡需要注意的是,在Python 2 中,如果一個類的方法不需要self引數,必須宣告為靜態方法,即加上@staticmethod裝飾器,從而不帶例項呼叫它。 而在Python 3中,如果一個類的方法不需要self引數,不再需要宣告為靜態方法,但是這樣的話只能通過類去呼叫這個方法,如果使用例項呼叫這個方法會引發異常。
>>> class person():
def __init__(self,name):
self.name = name
def say():
print('hi')
>>> person.say() #無需將類例項化,通過類直接呼叫
hi
>>> p=person('a')
>>> p.say() #不能通過例項直接呼叫
Traceback (most recent call last):
File "<pyshell#36>", line 1, in <module>
p.say()
TypeError: say() takes 0 positional arguments but 1 was given
>>>
@property 屬性方法
屬性方法:
-
把一個方法變成一個靜態屬性
-
可以訪問類變數和例項變數
-
只能通過例項呼叫,不能通過類呼叫
>>> class person(): def __init__(self,name): self.name = name @property def say(self): print('hi %s'%self.name) >>> a = person('a') #需將類例項化,不能通過類直接呼叫 >>> a.say hi a >>> class person(): n = 'nihao' def __init__(self,name): self.name = name @property def say(self): print('hi %s %s'%(self.name,self.n)) #可以訪問類變數和例項變數 >>> a = person('andy') >>> a.say hi andy nihao