繁体   English   中英

__init__和类变量的设置

[英]__init__ and the setting of class variables

我在理解类中的继承时遇到了一些麻烦,并且想知道为什么这部分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

我试图让动物检查是否实现了动物,然后如果这样做,则获取从动物继承的类以设置动物可以使用的变量。

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

现在,您可以通过说d1 = Dog(18)来创建一个简单的Dog对象,而无需使用d1 = Dog(Animal) ,您已经在第一行class Dog(Animal): d1 = Dog(Animal)告诉该类它的超类是Animalclass Dog(Animal):

  1. 创建一个类的实例

     mark = Dog() 

    mark = Dog(Animal)

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

     import abc class Animal(object): __metaclass__ = abc.ABCMeta def speak(self): ... 

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM