【发布时间】:2016-04-11 17:11:47
【问题描述】:
我正在尝试验证 2012 年 11 月 1 日 Python 教程 2.7.3 版第 9 章:类,第 66 页最后一行 (source) 中列出的实例属性和类属性之间的区别:
实例对象的有效方法名称取决于其类。经过 定义,作为函数对象的类的所有属性定义 其实例的相应方法。所以在我们的例子中,x.f 是一个 有效的方法参考,因为 MyClass.f 是一个函数,但 x.i 不是, 因为 MyClass.i 不是。 但是 x.f 和 MyClass.f 不是一回事—— 它是一个方法对象,而不是一个函数对象。
我有这个:
class MyClass:
"""A simple example class"""
i = 12345
def f():
return 'hello world'
然后我这样做:
>>> x = MyClass()
>>> x.f
<bound method MyClass.f of <__main__.MyClass instance at 0x02BB8968>>
>>> MyClass.f
<unbound method MyClass.f>
>>> type(MyClass.f)
<type 'instancemethod'>
>>> type(x.f)
<type 'instancemethod'>
注意x.f 和MyClass.f 的类型都是instancemethod。类型没有区别,但教程另有说明。有人可以澄清一下吗?
【问题讨论】:
标签: python class methods instance