Search code examples
pythonfunctionclassvariablesself

how do I properly print a sentence using variables defined in my own class in python


So I created a class in python called Pizza, which takes 4 arguments...I want to be able to insert the arguments and then print it so that it comes out in a clean sentence. For example if I put this into the terminal---

from Pizza import Pizza
appetizer = Pizza("Pepperoni", 16, 10.50, 10)
print(appetizer)

I would want to get this result--- Your Pepperoni pizza has a diameter of 16 inches, a price of $10.5, and 10 slices per pie

Unfortunately, with my code I keep getting this when I print out the variable---

<Pizza.Pizza object at 0x7f17b762f650>

Anyone know why this is happening? My code is below

class Pizza:
    def __init__(self, name, diameter, price, slices):
        self.name = name
        self.diameter = diameter
        self.price = price
        self.slices = slices
    def myfunc(self):
        print("Your" +  self.name + "pizza has a diameter of" + self.diameter + "inches, a price of" + self.price + "and" + self.slices + "slices per pie")

Solution

  • try

    from Pizza import Pizza
    appetizer = Pizza("Pepperoni", 16, 10.50, 10).myfunc()
    #you don't need to print appetizer because myfunc does it already
    

    and also, change class Pizza to this

    class Pizza:
        def __init__(self, name, diameter, price, slices):
            self.name = name
            self.diameter = diameter
            self.price = price
            self.slices = slices
        def myfunc(self):
            print("Your " +  self.name + " pizza has a diameter of " + str(self.diameter) + " inches, a price of " + str(self.price) + " and " + str(self.slices) + " slices per pie")
    

    so it doesn't cause a "TypeError: can only concatenate str (not "int") to str" error