ryan doucette ryan doucette - 2 years ago 113
Python Question

How do I call on a parent class in a subclass?

I need to create an UNBOUND method call to Plant to setup name and leaves and I don't know how. Any help is appreciated.

My code:

class Plant(object):
def __init__(self, name : str, leaves : int):
self.plant_name = name
self.leaves = leaves
def __str__(self):
return "{} {}".format(self.plant_name, self.leaves)
def __eq__(self, plant1):
if self.leaves == plant1.leaves:
return self.leaves
def __It__(self, plant1):
if self.leaves < plant1.leaves:
print ("{} has more leaves than {}".format(plant1.plant_name, self.plant_name))
return self.leaves < plant1.leaves
elif self.leaves > plant1.leaves:
print ("{} has more leaves than {}".format(self.plant_name, plant1.plant_name))
return self.leaves < plant1.leaves

class Flower(Plant):
def __init__(self, color : str, petals : int):
self.color = color
self.petals = petals

def pick_petal(self.petals)
self.petals += 1

Exact wording of the assignment:

Create a new class called Flower. Flower is subclassed from the Plant class; so besides name, and leaves, it adds 2 new attributes; color, petals. Color is a string that contains the color of the flower, and petal is an int that has the number of petals on the flower. You should be able to create an init method to setup the instance. With the init you should make an UNBOUND method call to plant to setup the name and leaves. In addition, create a method called pick_petal that decrements the number of petals on the flower.

Answer Source

The wording of the assignment is very strange. An "unbound method call" means you're calling a method on the class rather than on an instance of the class. That means something like Plant.some_method.

The only sort of unbound call that makes sense in this context is to call the __init__ method of the base class. That seems to fulfill the requirement to "setup the names and leaves".

It looks like this:

class Flower(Plant):
    def __init__(self, name, leaves, color, petals):
        Plant.__init__(self, ...)

You will need to pass in the appropriate arguments to __init__. The first is self, the rest are defined by Plant.__init__ in the base class. You'll also need to fix the syntax for the list of arguments, as `color : str' is not valid python.

Note: generally speaking, a better solution is to call super rather than doing an unbound method call on the parent class __init__. I'm not sure what you can do with that advice, though. Maybe the instructor is having you do inheritance the old way first before learning the new way?

For this assignment you should probably use Plant.__init__(...) since that's what the assignment is explicitly asking you to do. You might follow up with the instructor to ask about super.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download