Python Forum
I'm trying to make a constructor without hardcoding all of the values
Thread Rating:
  • 2 Vote(s) - 4 Average
  • 1
  • 2
  • 3
  • 4
  • 5
I'm trying to make a constructor without hardcoding all of the values
#1
I'm new to Python Classes. I'm trying to tell the constructor to associate a size with a price, but it's not liking it.

Here is the module code (PublicPizzaClass.py) with the class constructor in it:
#!/usr/bin/env python3
#PublicPizzaClass.py

class Pizza:
    #a constructor that initializes 3 attributes for any-topping pizzas.
    #right now, the attributes are public, so code outside of this class
    #will be able to get and set the values of these attributes.
    def __init__(pizza, name, size, price, taxPercent):
        pizza.name = name
        pizza.size = size #small = $7, medium = $9, large = $10
        pizza.price = getSizePrice()

    #a method that associates a size with a price
    def getSizePrice(pizza):
        if pizza.size == "Small":
            pizza.price = 7.00
        elif pizza.size == "Medium":
            pizza.price = 9.00
        elif pizza.size == "Large":
            pizza.price = 10.00
        return pizza.price

    #a method that uses two attributes to perform a calculation
    def getTaxAmount(pizza):
        pizza.price = getSizePrice()
        return pizza.price * 0.05

    #a method that calls another method to perform a calculation
    def getTotalPrice(pizza):
        return pizza.price + getTaxAmount()
And here is the code (PublicPizzaClassUser.py) that I'm trying to get to use the module's code:
#!/usr/bin/env python3
#PublicPizzaClassUser.py

#import the class from the PublicPizzaClass module
from PublicPizzaClass import Pizza

#create two pizza objects
pizza1 = Pizza("Pepperoni", "Large", getSizePrice())
pizza2 = Pizza("Sausage", "Medium", getSizePrice())

print("Name:            {:s}".format(pizza1.name))
print("Price:           {:.2f}".format(pizza1.getSizePrice()))
print("Tax Amount:      {:.2f}".format(pizza1.getTaxAmount()))
print("Total Price:     {:.2f}".format(pizza1.getTotalPrice()))
The error is:
Error:
==== RESTART: I:/Python/Python36-32/SamsPrograms/PublicPizzaClassUser.py ==== Traceback (most recent call last): File "I:/Python/Python36-32/SamsPrograms/PublicPizzaClassUser.py", line 8, in <module> pizza1 = Pizza("Pepperoni", "Large", getSizePrice()) NameError: name 'getSizePrice' is not defined
It's starting to look like using function calls to define constructor attributes is a no-no. Is that correct?
Reply
#2
I also tried this code. it seems there is no error but unfortunately don't work. Angry
Reply
#3
Here is a working version
#!/usr/bin/env python3
#PublicPizzaClass.py
 
class Pizza:
    #a constructor that initializes 3 attributes for any-topping selfs.
    #right now, the attributes are public, so code outside of this class
    #will be able to get and set the values of these attributes.
    def __init__(self, name, size, price=None, taxPercent=0.05):
        self.name = name
        self.size = size #small = $7, medium = $9, large = $10
        self.taxPercent = taxPercent
        self.price = self.getSizePrice(size) if price is None else price
        
    #a method that associates a size with a price
    @staticmethod
    def getSizePrice(size):
        if size == "Small":
            price = 7.00
        elif size == "Medium":
            price = 9.00
        elif size == "Large":
            price = 10.00
        return price
 
    #a method that uses two attributes to perform a calculation
    def getTaxAmount(self):
        return self.price * self.taxPercent
 
    #a method that calls another method to perform a calculation
    def getTotalPrice(self):
        return self.price + self.getTaxAmount()
    
 
#create two pizza objects
pizza1 = Pizza("Pepperoni", "Large")
pizza2 = Pizza("Sausage", "Medium")
 
print("Name:            {:s}".format(pizza1.name))
print("Price:           {:.2f}".format(pizza1.price))
print("Tax Amount:      {:.2f}".format(pizza1.getTaxAmount()))
print("Total Price:     {:.2f}".format(pizza1.getTotalPrice()))
Note that the implicit first argument in methods is usually named 'self' instead of 'pizza'. In this version, the constructor gives you the opportunity to give a price and tax percent, but if you don't give it, it chooses the default (price from size and tax 0.05).
Reply
#4
Next problem. My book has showed the different options for constructors, and how to use values of an object created with those constructors. I understand how to create a function that does things with the values from an object instance, but I'm not sure what to make of this:
def methodName(self[, parameters]):
    statements
The square brackets look really weird. In my attempt to try to create my own example, this is what I came up with:
#!/usr/bin/env python3
#PublicPizzaClass.py

##class Pizza:
##    #a constructor that initializes 4 attributes for any-topping pizzas.
##    #right now, the attributes are public, so code outside of this class
##    #will be able to get and set the values of these attributes.
##    def __init__(pizza, name, size, price):
##        pizza.name = name
##        pizza.size = size #small = $7, medium = $9, large = $10
##        pizza.price = price

def Pizza(pizza[, name, size, price]):
    pizza.name = name
    pizza.size = size
    pizza.price = price

    #a method that uses two attributes to perform a calculation
    def getTaxAmount(pizza):
        return pizza.price * 0.05

    #a method that calls another method to perform a calculation
    def getTotalPrice(pizza):
        return pizza.price + pizza.getTaxAmount()
After running this python file:
#!/usr/bin/env python3
#PublicPizzaClassUser.py

#import the class from the PublicPizzaClass module
from PublicPizzaClass import Pizza

#create two pizza objects
pizza1 = Pizza("Pepperoni", "Large", 10.00)
pizza2 = Pizza("Sausage", "Medium", 9.00)

myPizza = pizza1.name
print(myPizza)#should print "Pepperoni"
The error I got was:
Error:
==== RESTART: I:/Python/Python36-32/SamsPrograms/PublicPizzaClassUser.py ==== Traceback (most recent call last): File "I:/Python/Python36-32/SamsPrograms/PublicPizzaClassUser.py", line 5, in <module> from PublicPizzaClass import Pizza File "I:/Python/Python36-32/SamsPrograms\PublicPizzaClass.py", line 13 def Pizza(pizza[, name, size, price]): ^ SyntaxError: invalid syntax
Seriously, what is up with the method that encloses its parameters in square brackets? If that type of method isn't supposed to act as a constructor, what is it for?
Reply
#5
Thanks for considering me you have made this very good !
but it doesn't take any argument as a input
Reply
#6
(Apr-05-2018, 05:30 AM)Gribouillis Wrote: Here is a working version
        self.price = self.getSizePrice(size) if price is None else price
Note that the implicit first argument in methods is usually named 'self' instead of 'pizza'. In this version, the constructor gives you the opportunity to give a price and tax percent, but if you don't give it, it chooses the default (price from size and tax 0.05).
I don't see anything like
price = input("Specify a price: ")
in there, so what part of that line of your code above allows the user to choose a price?
Reply
#7
(Apr-05-2018, 05:53 AM)RedSkeleton007 Wrote: what part of that line of your code above allows the user to choose a price?
The code that uses the class can choose the price. One can write
pizza1 = Pizza("Pepperoni", "Large")
pizza1 = Pizza("Pepperoni", "Large", 12.0)
pizza1 = Pizza("Pepperoni", "Large", price=12.0)
pizza1 = Pizza("Pepperoni", "Large", taxPercent=0.07)
pizza1 = Pizza("Pepperoni", "Large", price=11.0, taxPercent=0.06)

(Apr-05-2018, 05:36 AM)RedSkeleton007 Wrote: what is up with the method that encloses its parameters in square brackets?
This syntax is only used in the documentation to indicate optional arguments. It is not valid syntax in real code.
Reply
#8
class Pizza():
    def __init__(self, name, size):
        self.name = name.capitalize()
        self.size = size.lower()
    
    @property
    def price(self):
        prices = {'Margherita':{'small':7.00, 'medium':9.00, 'large':11.00},
                  'Pepperoni':{'small':8.00, 'medium':10.00, 'large':12.00}}
        return prices[self.name][self.size]
        
    def __str__(self):
        return ('{} {}'.format(self.size, self.name))
                  
small_margherita = Pizza('Margherita', 'small')
large_pepperoni = Pizza('pepperoni', 'large')

print('{}, price: {:.2f}'.format(small_margherita, small_margherita.price))
print('{}, price: {:.2f}'.format(large_pepperoni, large_pepperoni.price))
Output:
small Margherita, price: 7.00 large Pepperoni, price: 12.00
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Why doesn't calling a parent constructor work with arbitrary keyword arguments? PurposefulCoder 4 1,041 Jun-24-2023, 02:14 PM
Last Post: deanhystad
  Simple Python API, need packaging/removing hardcoding zxcv101 2 1,211 Jun-13-2022, 03:09 PM
Last Post: zxcv101
  Not including a constructor __init__ in the class definition... bytecrunch 3 12,332 Sep-02-2021, 04:40 AM
Last Post: deanhystad
  How to make a list of values from a dictionary list? faryad13 2 2,134 Sep-03-2020, 03:45 PM
Last Post: faryad13
  syntaxerror when entering a constructor MaartenRo 2 2,044 Aug-03-2020, 02:09 PM
Last Post: MaartenRo
  error in constructor overriding in python3 srm 1 1,871 Jul-18-2019, 12:21 PM
Last Post: ichabod801
  This constructor takes no arguments Friend 2 5,408 Jun-26-2019, 02:54 PM
Last Post: Friend
  class constructor with dataframe UGuntupalli 2 2,373 Jun-11-2019, 10:50 PM
Last Post: UGuntupalli
  Overload of constructor psosmol 2 2,861 Apr-17-2019, 05:10 AM
Last Post: psosmol
  How to Make Python code execution pause and resume to create .csv and read values. Kashi 2 3,841 Jun-14-2018, 04:16 PM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

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