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):
要创建一个类的实例
mark = Dog()
Run Code Online (Sandbox Code Playgroud)
没有mark = Dog(Animal).
不要做这个implimented东西.如果你想要一个你无法实例化的类(即你必须先进行子类化),那就去做吧
import abc
class Animal(object):
__metaclass__ = abc.ABCMeta
def speak(self):
...
Run Code Online (Sandbox Code Playgroud)