0

我在理解类中的继承时遇到了一些麻烦,并且想知道为什么这段 python 代码不起作用,谁能告诉我这里出了什么问题?

## Animal is-a object 
class Animal(object):
    def __init__(self, name, sound):
        self.implimented = False
        self.name = name
        self.sound = sound

    def speak(self):
        if self.implimented == True:
            print "Sound: ", self.sound

    def animal_name(self):
        if self.implimented == True:
            print "Name: ", self.name



## Dog is-a Animal
class Dog(Animal):

    def __init__(self):
        self.implimented = True
        name = "Dog"
        sound = "Woof"

mark = Dog(Animal)

mark.animal_name()
mark.speak()

这是通过终端的输出

Traceback (most recent call last):
  File "/private/var/folders/nd/4r8kqczj19j1yk8n59f1pmp80000gn/T/Cleanup At Startup/ex41-376235301.968.py", line 26, in <module>
    mark = Dog(Animal)
TypeError: __init__() takes exactly 1 argument (2 given)
logout

我试图让动物检查是否实现了动物,然后如果是,则获取从动物继承的类以设置动物随后能够操作的变量。

4

3 回答 3

6

katrielalex 很好地回答了您的问题,但我还想指出,您的课程编码有些糟糕 - 如果不是错误的话。关于你使用类的方式似乎很少有误解。

首先,我建议阅读 Python 文档以了解基本概念:http ://docs.python.org/2/tutorial/classes.html

要创建一个类,您只需执行

class Animal:
    def __init__(self, name, sound): # class constructor
        self.name = name
        self.sound = sound

a1 = Animal("Leo The Lion", "Rawr")现在您可以通过调用或调用来创建名称对象。

要继承一个类,你可以:

# Define superclass (Animal) already in the class definition
class Dog(Animal):

    # Subclasses can take additional parameters, such as age
    def __init__(self, age):

        # Use super class' (Animal's) __init__ method to initialize name and sound
        # You don't define them separately in the Dog section
        super(Dog, self).__init__("Dog", "Woof")

        # Normally define attributes that don't belong to super class
        self.age = age

现在你可以Dog通过说创建一个简单的对象d1 = Dog(18)并且你不需要使用d1 = Dog(Animal),你已经告诉类它的超类Animal在第一行class Dog(Animal):

于 2012-12-03T14:06:11.613 回答
5
  1. 要创建一个类的实例,你要做

    mark = Dog()
    

    不是mark = Dog(Animal)

  2. 不要做这种事implimented。如果您想要一个无法实例化的类(即您必须先进行子类化),请执行

    import abc
    class Animal(object):
        __metaclass__ = abc.ABCMeta
    
        def speak(self):
            ...
    
于 2012-12-03T13:55:39.297 回答
1

由于给定示例中的年龄不是父(或)类的一部分,因此您必须在继承的类(也称为派生类)中实现函数(在类中称为方法)。

class Dog(Animal):

    # Subclasses can take additional parameters, such as age
    def __init__(self, age):
        ... # Implementation can be found in reaction before this one

    def give_age( self ):
        print self.age
于 2012-12-03T14:21:28.413 回答