Polymorphism Python -


i learning python , have question . after running code ,the result displayed

"name bob , salary is50000 , work main.pizzarobot object @ 0x00000000028eecc0>>"

i want "work" displayed each object in str rather calling obj.work() each object .

in problem output should "name bob , salary is50000 , work bob makes pizza"

thanks

class employee():     def __init__(self,name,salary = 0):         self.name = name         self.salary = salary     def giveraise(self,percent):         self.salary = self.salary + self.salary * percent     def __str__(self):         return "name {0} , salary is{1} , work {2}".format(self.name,self.salary,self.work)     def work(self):         print(self.name ,"does stuff")  class chef(employee):      def __init__(self,name):          employee.__init__(self,name,50000)      def work(self):          print(self.name ,"makes food")  class pizzarobot(chef):      def __init__(self,name):          chef.__init__(self,name)      def work(self):          print(self.name ,"makes pizza")  if __name__ == "__main__":     bob = pizzarobot("bob")     print(bob) 

self.work function, behaviour.

in work functions, instead of doing print, use return:

 def work(self):      return self.name + " makes food") 

and then, can use

return "name {0} , salary is{1} , work {2}".format(self.name,self.salary,self.work()) 

(note () @ end, self.work(). call function)


Comments

Popular posts from this blog

java - Oracle EBS .ClassNotFoundException: oracle.apps.fnd.formsClient.FormsLauncher.class ERROR -

c# - how to use buttonedit in devexpress gridcontrol -

nvd3.js - angularjs-nvd3-directives setting color in legend as well as in chart elements -