__初始化和类变量的设置

2024-09-30 12:21:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我在理解类中的继承时遇到了一些困难,我想知道为什么这段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()

这是通过终端的输出

^{pr2}$

我试图让animal检查是否实现了一个animal,如果实现了,让从animal继承的类来设置动物可以操作的变量。在


Tags: nameselftrueobjectinitisdefclass
3条回答

Katriealex很好地回答了你的问题,但我也要指出,你的类即使没有错误的编码也有点糟糕。对你使用类的方式似乎没有什么误解。在

首先,我建议您阅读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")来创建name对象。在

要继承类,请执行以下操作:

^{pr2}$

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

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

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
  1. 创建类的实例

    mark = Dog()
    

    不是mark = Dog(Animal)

  2. 不要做这种事。如果你想要一个你不能实例化的类(也就是说,你必须先子类化),那么

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

相关问题 更多 >

    热门问题