简体   繁体   中英

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:

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!

Here's what your code should look like for all the methods to be in the Animal class:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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