Python Forum

Full Version: Help needed with polymorphism example
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi community,

I am trying to implement some polymorhphism concepts. In the study material I am using, there is a similar example. There is no __init__ method in the sample example.

I want to define 2 types of flowers - one which can be cleaned only by spraying some water and others where the petals need to cleaned one by one.

Depending on the subclass, I want the appropriate method to be invoked. Below is my code and below is the error, can you please help:

class Flowers:
    def cleaningTask():
        pass

    def performCleaningTask():
        cleaningTask()
class petalFlowers(Flowers):
    def cleanThePetals():
        print("petals are cleaned")

    def cleaningTask():
        cleanThePetals()
        
class sprayFlowers(Flowers):
    def sprayWater():
        print("only water is sprayed")

    def cleaningTask():
        sprayWater()
Error:
>>> rose=petalFlowers() >>> rose.performCleaningTask() Traceback (most recent call last): File "<pyshell#67>", line 1, in <module> rose.performCleaningTask() TypeError: performCleaningTask() takes 0 positional arguments but 1 was given
There are two related problems in your classes. First, every class method must have at least one argument because the class instance is passed in as the first argument to a method. By convention, "self" is the name for this required argument.

Related to that, any time you call a method from the same class, you must call it as "self.method". Otherwise, that will return an error as well.

class Flowers:
    def cleaningTask(self):
        pass
 
    def performCleaningTask(self):
        self.cleaningTask()

class petalFlowers(Flowers):
    def cleanThePetals(self):
        print("petals are cleaned")
 
    def cleaningTask(self):
        self.cleanThePetals()
         
class sprayFlowers(Flowers):
    def sprayWater(self):
        print("only water is sprayed")
 
    def cleaningTask(self):
        self.sprayWater()
Thank you so much. They should not make such implicit assumptions while giving examples to newbies, or we get stuck :( Openedg PCAP2, chapter 5 examples.