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?
Ronan Boiteau
10.3k7 gold badges40 silver badges62 bronze badges
-
2Works for me when I fix your indentation: repl.it/repls/PleasingRealisticEelBlorgbeard– Blorgbeard2018年01月12日 21:48:27 +00:00Commented Jan 12, 2018 at 21:48
-
2Your indentation is broken here and probably wrong in your task code. I expect you won't be able to access getName on a base Animal instance either.Daniel Roseman– Daniel Roseman2018年01月12日 21:50:01 +00:00Commented Jan 12, 2018 at 21:50
-
1I indented your code in an edit and it should work fine. Please close this if it does workJacobIRR– JacobIRR2018年01月12日 21:50:22 +00:00Commented Jan 12, 2018 at 21:50
-
Also note, writing getters and setters is not Pythonic.Daniel Roseman– Daniel Roseman2018年01月12日 21:50:41 +00:00Commented Jan 12, 2018 at 21:50
-
One of the first things you should have learned when starting Python is that it's critical to get the indentation correct.Barmar– Barmar2018年01月12日 21:51:02 +00:00Commented Jan 12, 2018 at 21:51
1 Answer 1
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.
answered Jan 12, 2018 at 21:52
Ronan Boiteau
10.3k7 gold badges40 silver badges62 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-py