【问题标题】:Python: class instance created with no argumentPython:没有参数创建的类实例
【发布时间】:2019-02-11 22:36:48
【问题描述】:

当我声明一个类时,比如说,

class MyClass: 
    def __init__(self, value):
        self.data = value 
    def show(self):
        print self.data`

然后创建一个实例

A = MyClass(1)

表现如我所料(A.show 的输出是1)。但是当我创建一个没有参数的实例时

B = MyClass

然后手动设置值

B.data = 2 

调用B.show 返回TypeError: unbound method show() must be called with MyClass instance as first argument (got nothing instead)

谁能解释一下为什么?

【问题讨论】:

  • B = MyClass 不创建实例。它将类对象分配给标识符B。你需要B = MyClass()(会抛出错误)
  • 那不是创建实例。
  • 不带参数的正确创建方法是这样的:B = MyClass(),但这不起作用,因为编写的__init__() 方法要求您提供value 参数。如果你给value 一个默认的def __init__(self, value=None): 你可以做B = MyClass() 没有问题。

标签: python methods


【解决方案1】:

B 是类定义 MyClass 的另一个名称。

B.data = 2

在类定义上创建一个名为 data 的属性。

B.show 是对MyClass 上定义的函数的引用。它是一个实例函数,并期望在 MyClass 的实例上调用(这是 A 是什么,但不是 B 是什么)。

实例作为第一个参数隐式传递给函数。您可以使用实例显式调用该函数:

B.show(A)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-15
    • 2015-08-13
    相关资源
    最近更新 更多