I've created an "Animal" class that takes in parameters name
and colour
, and a subclass called "Pig" which should inherit name
and colour
from "Animal", but should also take a new parameter, TailType
.
Here's what I've done so far:
class Animal(object):
def __init__(self, name, colour):
self.name = name
self.colour = colour
def get_name(self):
return self.name
def set_name(self, newName = ""):
self.name = newName
def set_colour(self, newColour = ""):
self.colour = newColour
def get_colour(self):
return self.colour
def __str__(self):
return self.get_name() + ' : ' + self.colour
class Pig(Animal):
def __init__(self, name, colour, tailType):
super().__init__()
self.tailType = tailType
When I'm initialising the "Pig" class, I'm not sure which parameters to put in the __init__
definition; should it be name
and colour
, or name
+ colour
+ tailType
?
Also, does this subclass inherit the __str__
representation method of Animal, or do I have to write that again within the "Pig" subclass?
I'm really not sure about which parameters go where, when I initialise a subclass. I've looked at examples, and they all have very simple cases with one parameter (self).
If I try to do
john = Pig('John', 'pink', 'curly')
I get
TypeError: __init__() missing 2 required positional arguments: 'name' and 'colour'
.
Superclasses and subclasses make sense conceptually, but when it comes to dealing with their syntax, I'm really struggling.
Note: please don't refer me to a general explanation of what superclass constructors are: I've read a lot of them and still don't really know how to apply them in this situation.
Just pass name
and colour
.
class Pig(Animal):
def __init__(self, name, colour, tailType):
super().__init__(name, colour)
self.tailType = tailType
Think of it as super()
provides me the method from the parent, bound to my object. What does it take as inputs? name
and colour
? Let's pass it name
and colour
, then.
And yes, __str__
is inherited like any other method.