python 普通方法、靜態方法和類方法有什麼區別?
阿新 • • 發佈:2019-01-29
下面用例子的方式,說明其區別。
首先, 定義一個類,包括3個方法:
class Apple(object):
def get_apple(self, n):
print "apple: %s,%s" % (self,n)
@classmethod
def get_class_apple(cls, n):
print "apple: %s,%s" % (cls,n)
@staticmethod
def get_static_apple(n):
print "apple: %s" % n
類的普通方法
類的普通方法,需要類的例項呼叫。
a = Apple()
a.get_apple(2)
輸出結果
apple: <__main__.Apple object at 0x7fa3a9202ed0>,2
再看繫結關係:
print (a.get_apple)
<bound method Apple.get_apple of <__main__.Apple object at 0x7fa3a9202ed0>>
類的普通方法,只能用類的例項去使用。如果用類呼叫普通方法,出現如下錯誤:
Apple.get_apple(2)
Traceback (most recent call last):
File "static.py", line 22, in <module>
Apple.get_apple(2)
TypeError: unbound method get_apple() must be called with Apple instance as first argument (got int instance instead)
類方法
類方法,表示方法繫結到類。
a.get_class_apple(3)
Apple.get_class_apple(3 )
apple: <class '__main__.Apple'>,3
apple: <class '__main__.Apple'>,3
再看繫結關係:
print (a.get_class_apple)
print (Apple.get_class_apple)
輸出結果,用例項和用類呼叫是一樣的。
<bound method type.get_class_apple of <class '__main__.Apple'>>
<bound method type.get_class_apple of <class '__main__.Apple'>>
靜態方法
靜態方法,實際上就是一個方法。
a.get_static_apple(4)
Apple.get_static_apple(4)
apple: 4
apple: 4
再看繫結關係
print (a.get_static_apple)
print (Apple.get_static_apple)
輸出結果
<function get_static_apple at 0x7fa3a92078c0>
<function get_static_apple at 0x7fa3a92078c0>