0
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
asked Jan 12, 2018 at 21:45
9
  • 2
    Works for me when I fix your indentation: repl.it/repls/PleasingRealisticEel Commented Jan 12, 2018 at 21:48
  • 2
    Your 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. Commented Jan 12, 2018 at 21:50
  • 1
    I indented your code in an edit and it should work fine. Please close this if it does work Commented Jan 12, 2018 at 21:50
  • Also note, writing getters and setters is not Pythonic. Commented 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. Commented Jan 12, 2018 at 21:51

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.