Python类:功能或实例方法



我正在学习使用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'>

进行研究后,我发现类型InstanceMethod与界定原因不同。另外,我的jupyter笔记本正在运行python3,但我的教科书是一个较旧的版本,该版本是用python2编写的。

这两个差异主要是因为您所关注的书已被写为python2.x。如果您测试了该书的代码,请说使用Python2.7.x,您将获得同一本书的输出:

(<type 'type'>, <type 'instancemethod'>)

实际上,如果您的类不会从对象继承,并且它像class IntSet:一样定义,则使用Python2.7.x时会得到以下输出:

(<type 'classobj'>, <type 'instancemethod'>)

当您使用Python 3.6.x时,无论您是否从对象继承,您都可以得到:

<class 'type'> <class 'function'>

基本上是因为python3使用了新样式的类,因此您的类是否从对象继承,它仍然是 new> new Style 类。另外,如果您打算代码,从对象继承被认为是一个好习惯使用Python2和Python3进行运行。

是的,您这一边没错,只是Python2和Python3之间的区别之一。

ns:此https://wiki.python.org/moin/fromfunctionTomethod也可能会进一步阐明您的问题。

最新更新