繁体   English   中英

Python类:函数或实例方法

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM