[英]Python 3.6.0 Class Inheritance
class Animal:
def __init__(self, name, species):
self.name = name
self.species = species
def getName(self):
return self.name
def getSpecies(self):
return self.species
def __del__(self):
print ("This came from del method")
class Dog(Animal):
pass
def __init__(self, name, isBig):
Animal.__init__(self, name, "Dog")
self.isBig = isBig
I've been playing around with understanding Classes and Child Classes and ran into the following. 我一直在学习理解班级和儿童班级,并遇到以下问题。 When instantiating
实例化时
dog = Dog("Bob", True)
and try to access the method getName() from the parent, Animal, class I get the following error: 并尝试从父类Animal类访问方法getName(),我得到以下错误:
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
dog.getName()
AttributeError: Dog instance has no attribute 'getName'
What is preventing me from directly accessing methods of the parent class? 是什么使我无法直接访问父类的方法?
Don't forget that indentation matters in Python! 不要忘记缩进在Python中很重要!
Here's what your code should look like for all the methods to be in the Animal
class: 这是在
Animal
类中包含所有方法的代码的样子:
class Animal:
def __init__(self, name, species):
self.name = name
self.species = species
def getName(self):
return self.name
def getSpecies(self):
return self.species
def __del__(self):
print ("This came from del method")
If you miss an indentation block, Python thinks you're done with your class definition. 如果您错过了一个缩进块,Python会认为您已经完成了类定义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.