1

I am learning python and have question . After running this code ,the result displayed is

"Name is Bob and salary is50000 and work is main.PizzaRobot object at 0x00000000028EECC0>>"

I want "work" to be displayed for each object in str rather than calling obj.work() for each object .

In this problem output should be "Name is Bob and salary is50000 and work is 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 is {0} and salary is{1} and work is {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)
1
  • you should use super().__init__(name,50000) and give each class an occupation attribute Commented Nov 19, 2014 at 11:34

1 Answer 1

1

self.work is a function, thus your behaviour.

In the work functions, instead of doing a print, use return:

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

And then, you can use

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

(note the () at the end, self.work(). You will call the function)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.