[英]Python Class: function or instance method
我正在使用一本名為《使用Python計算和編程入門》的教科書來學習Python,在第8章中有一個示例代碼:
class IntSet(object):
"""An intSet is a set of integers"""
# Information about the implementation (not the abstraction)
# The value of the set is represented by a list of ints, self.vals.
# Each int in the set occurs in self.vals exactly once.
def __init__(self):
"""Create and empty set of integers"""
self.vals == []
def insert(self, e):
"""Assumes e is an integer and inserts e into self"""
if not e in self.vals:
self.vals.append(e)
"""I've omitted this part of the example code"""
def __str__(self):
"""Returns a string representation of self"""
self.vals.sort()
result = ''
for e in self.vals:
result = result + str(e) + ','
return '{' + result[:-1] + '}' # -1 omits trailing comma
教科書上說:
print(type(IntSet), type(IntSet.insert))
將打印:
<type 'type'> <type 'instancemethod'>
還沒有我的照片:
<class 'type'> <class 'function'>
經過研究,我發現由於實例限制,實例方法的類型不同於函數。 另外,我的Jupyter Notebook正在運行Python3,但我的教科書是使用Python2編寫的較舊版本。
兩者的差異主要是因為您所遵循的書在編寫時緊隨其后是python2.x。 如果您測試了該書的代碼,例如使用python2.7.x,您將獲得與該書完全相同的輸出:
(<type 'type'>, <type 'instancemethod'>)
實際上,如果您的類不會繼承自object,並且其定義類似於class IntSet:
使用python2.7.x時,您將獲得以下輸出:
(<type 'classobj'>, <type 'instancemethod'>)
如果您使用的是python 3.6.x,無論您是否繼承自object,都將得到:
<class 'type'> <class 'function'>
這基本上是因為python3使用新型類 ,所以您的類是否從對象繼承都沒有關系,它仍然是新型類。 另外,如果您打算將代碼同時與python2和python3一起運行,則從對象繼承被認為是一種好習慣。
是的,這沒錯,只是python2和python3之間的區別之一。
NS:這個https://wiki.python.org/moin/FromFunctionToMethod也可以進一步闡明您的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.