我在理解类中的继承时遇到了一些困难,我想知道为什么这段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继承的类来设置动物可以操作的变量。在
Katriealex很好地回答了你的问题,但我也要指出,你的类即使没有错误的编码也有点糟糕。对你使用类的方式似乎没有什么误解。在
首先,我建议您阅读Python文档以获得基本思想:http://docs.python.org/2/tutorial/classes.html
要创建一个类,只需
现在您可以通过调用
a1 = Animal("Leo The Lion", "Rawr")
来创建name对象。在要继承类,请执行以下操作:
^{pr2}$现在,您可以通过说
d1 = Dog(18)
来创建一个简单的Dog
对象,而不需要使用d1 = Dog(Animal)
,您已经在第一行class Dog(Animal):
告诉类它的超类是Animal
由于给定示例中的age不是父类(或基)类的一部分,因此必须在继承的类(也称为派生的类)中实现函数(在类中称为方法)。在
创建类的实例
不是
mark = Dog(Animal)
。不要做这种事。如果你想要一个你不能实例化的类(也就是说,你必须先子类化),那么
相关问题 更多 >
编程相关推荐