Python Forum
Help needed with polymorphism example
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help needed with polymorphism example
#1
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
Reply
#2
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()
Reply
#3
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.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020