python类方法是什么_python类方法和普通方法区别是什么
python類方法和普通方法區別是什么
發布時間:2020-09-10 10:19:43
來源:億速云
閱讀:62
作者:小新
這篇文章將為大家詳細講解有關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)
>
類的普通方法,只能用類的實例去使用。如果用類調用普通方法,出現如下錯誤:Apple.get_apple(2)
Traceback (most recent call last): File "static.py", line 22, in 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: ,3
apple: ,3
再看綁定關系:print (a.get_class_apple) print (Apple.get_class_apple)
輸出結果,用實例和用類調用是一樣的。> >
關于python類方法和普通方法區別是什么就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
總結
以上是生活随笔為你收集整理的python类方法是什么_python类方法和普通方法区别是什么的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 本地共享映射文件夹进行删除操作_从集群建
- 下一篇: java length()函数_小猿圈介