我的课认为"自我"是一个需要赋值的论证

0 python inheritance

我不确定为什么会这样.似乎认为"自我"需要一个论证,这没有任何意义.

这是我的代码:

class Animal:

    def __init__(self):
        self.quality = 1


class Bear(Animal):

    def __init__(self):
        Animal.__init__(self)

    def getImage(self):
        return "bear.ppm"

class Fish(Animal):

    def __init__(self):
        Animal.__init__(self)

    def getImage(self):
        return "fish.ppm"
Run Code Online (Sandbox Code Playgroud)

而我得到的错误是:

Traceback (most recent call last):

  File "<pyshell#1>", line 1, in <module>
    Bear.getImage()

TypeError: getImage() takes exactly 1 argument (0 given)
Run Code Online (Sandbox Code Playgroud)

dan*_*ano 8

您必须Bear在致电之前实例化getImage():

b = Bear()
b.getImage()
Run Code Online (Sandbox Code Playgroud)

getImage是一个实例方法,因此它只被设计为在类的特定实例上调用Bear.该实例的状态是作为self变量传递的内容getImage.呼叫b.getImage()等同于:

b = Bear()
Bear.getImage(b)
Run Code Online (Sandbox Code Playgroud)

因此,如果没有实例Bear,则没有任何内容可用于self参数,这就是您在调用时看到异常的原因Bear.getImage().有关更多信息,请参阅有关Python实例方法的文档.

如果您希望能够调用getImage类Bear而不是特定实例,则需要使用@staticmethod装饰器使其成为静态方法:

class Bear(Animal):

    def __init__(self):
        Animal.__init__(self)

    @staticmethod
    def getImage():
        return "bear.ppm"
Run Code Online (Sandbox Code Playgroud)

然后你可以打电话Bear.getImage().