首頁  >  文章  >  後端開發  >  python類別方法和普通方法區別

python類別方法和普通方法區別

藏色散人
藏色散人原創
2019-07-03 09:45:033800瀏覽

python類別方法和普通方法區別

python類別方法和普通方法區別

下面用例子的方式,說明其區別。

首先, 定義一個類,包括2個方法:

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)

類別的普通方法

類別的普通方法,需要類別的實例調用。

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 &#39;__main__.Apple&#39;>,3
apple: <class &#39;__main__.Apple&#39;>,3

再看綁定關係:

print (a.get_class_apple) print (Apple.get_class_apple)

輸出結果,用實例和用類別呼叫是一樣的。

<bound method type.get_class_apple of <class &#39;__main__.Apple&#39;>> <bound method type.get_class_apple of <class &#39;__main__.Apple&#39;>>

相關推薦:《Python教學

以上是python類別方法和普通方法區別的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
上一篇:怎麼垂直輸出下一篇:怎麼垂直輸出