__init__和类变量的设置

ler*_*ray 0 python variables inheritance

我在理解类中的继承方面遇到了一些麻烦,并想知道为什么这些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()
Run Code Online (Sandbox Code Playgroud)

这是通过终端的输出

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
Run Code Online (Sandbox Code Playgroud)

我试图让动物检查一只动物是否被实施,然后如果是这样,让动物继承动物来设置动物可以操作的变量.

小智 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
Run Code Online (Sandbox Code Playgroud)

现在你可以通过调用来创建名称对象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
Run Code Online (Sandbox Code Playgroud)

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

  • @lerugray我从未确定LPTHW是否意味着模仿.我绝对不认为这是学习Python的方法.我建议[如何像计算机科学家一样思考](http://www.greenteapress.com/thinkpython/). (2认同)
  • 如果你想让你的每一只动物都有一个年龄,你可以在父类中定义`age`和`printAge`,`Animal`.如果你想让一些动物有一个年龄,你将从`Animal`继承`AgedAnimal`,它将实现`age`和`printAge`,然后从`AgedAnimal`继承`Dog`.如果只有`Dog`有年龄,你将`age`和`printAge`编码为`Dog`,并保持`Animal`不变. (2认同)
  • @lerugray你会在`Animal .__ init __()`-method中初始化`age`,是的.如果有两个或多个具有公共属性的类(例如`age`),则将common属性编码为其Base类. (2认同)

Kat*_*iel 5

  1. 要创建一个类的实例

    mark = Dog()
    
    Run Code Online (Sandbox Code Playgroud)

    没有mark = Dog(Animal).

  2. 不要做这个implimented东西.如果你想要一个你无法实例化的类(即你必须先进行子类化),那就去做吧

    import abc
    class Animal(object):
        __metaclass__ = abc.ABCMeta
    
        def speak(self):
            ...
    
    Run Code Online (Sandbox Code Playgroud)

  • @lerugray你不可能两种方式:如果你将动物定义为可以说话的东西,那么一只不能说话的考拉不是动物. (2认同)