Not sure if I made sense in the title, but I have created classes and now I need to associate a class with a number. For example 1 would be the penny (object) and with this object I have associated height and weight. I need help asking how to associate this class with the number 1.
I know i need to have it ask the question like something like so
print "Enter 1 for Penny\nEnter 5 for Nickel\nEnter 10 for Dime\nEnter 25 for Quarter\nEnter 50 for halfdollar\nEnter 100 for Dollar"
I need it to then ask me to Enter number:
Than ask how many of that coin of the number you just entered:
Than give me the total weight
Than give me the total height
with that should I include it in that original print statement or should I do another print statement or just keep it like so...
print "Enter 1 for Penny\nEnter 5 for Nickel\nEnter 10 for Dime\nEnter 25 for Quarter\nEnter 50 for halfdollar\nEnter 100 for Dollar\nEnter how many coins"
Now witht the last part of enter how many coins how do I associate that with a class I have a class set up for Penny for instance like so
#! /usr/bin/python
# Defining a class
class Coin():
def __init__(slef,weight,height):
self.weight = weight
self.height = height
class Penny(Coin)
def __init__(self)
Coin.__init__(self,2.500,1.52)
Penny = 1
class Nickel(Coin):
def __init__(self):
Coin.__init__(self,5.00,1.95)
Nicke = 5
class Dime(Coin):
def __init__(self):
Coin.__init__(self,2.268,1.35)
Dime = 10
class Quarter(Coin):
def __init__(self):
Coin.__init__(self,5.670,1.75)
Quarter = 25
class HalfDollar(Coin):
def __init__(self):
Coin.__init__(self,11.34,2.15)
HalfDollar = 50
class Dollar(Coin):
def __init__(self):
Coin.__init__(self,8.10,2.00)
Dollar = 100
print "Enter 1 for Penny\nEnter 5 for Nickel\nEnter 10 for Dime\nEnter 25 for Quarter\nEnter 50 for halfdollar\nEnter 100 for Dollar\n"
print "Please enter a number:"
If you name it something generic like cents, you can create a lookup table as follows:
lookup_table = {Penny.cents: Penny, Nickle.cents: Nickle, Dime.cents: Dime, ... }
coin = lookup_table[number_user_entered]()
That way you can dynamically create an instance of the proper class based on the user input.
I think what you are trying to do is something like this:
class Coin():
def __init__(self, name, value, weight, height):
self.name = name
self.value = value
self.weight = weight
self.height = height
definitions = [("dollar", 100, 8.1, 2.0), ...] # define the coins
coins = {data[1]: Coin(*data) for data in definitions} # create Coin instances
There is no need for the Dollar to be a sub-class of Coin, you can just make it an instance with appropriate attribute values.
You can now access each Coin instance within coins by value:
dollar = coins[100]
or use it to access the name:
for value in sorted(coins):
print("Enter {0.value} for a {0.name}".format(coins[value]))
coin_value = int(raw_input("Pick a coin: "))
coin = coins[coin_value]
coin_count = int(raw_input("How many {0}: ".format("{0.name}s".format(coin)
if coin.value > 1 else
"pennies")))
The other answers are both good other ways of dealing with your problem. To strictly solve it the way you defined it:
class Coin():
def __init__(self, weight, height):
self.weight = weight
self.height = height
class Penny(Coin):
value = 1
def __init__(self):
Coin.__init__(self, 2.500, 1.52)
class Nickel(Coin):
value=5
def __init__(self):
Coin.__init__(self, 5.00, 1.95)
class Dime(Coin):
value=10
def __init__(self):
Coin.__init__(self, 2.268, 1.35)
class Quarter(Coin):
value=25
def __init__(self):
Coin.__init__(self, 5.670, 1.75)
class HalfDollar(Coin):
value=50
def __init__(self):
Coin.__init__(self, 11.34, 2.15)
class Dollar(Coin):
value=100
def __init__(self):
Coin.__init__(self, 8.10, 2.00)
mycoin = Penny()
print "A penny is worth", mycoin.value
yourcoin = Quarter()
print "A quarter is worth", yourcoin.value
association = {str(class_obj.value): class_obj for class_obj in (Penny, Nickel, Dime, Quarter, HalfDollar, Dollar)}
print "Enter 1 for Penny\nEnter 5 for Nickel\nEnter 10 for Dime\nEnter 25 for Quarter\nEnter 50 for halfdollar\nEnter 100 for Dollar\n"
value = raw_input("Please enter a number:")
number = raw_input("How many of that coin:")
if value in association:
mycoin = association[value]()
print "total weight:", mycoin.weight * int(number)
print "total height:", mycoin.height * int(number)
How about storing the coin type and amount of coins into a dictionary of a single multidimensional list:
coins = {1:[Penny,[]], 5:[Nickel,[]], 10:[Dime,[]]} # etc...
Then, when you ask the user for coin type and amount, take that value as the key lookup for the dictionary and append that many coins to its list, instantiating the class in the process:
coin_type = raw_input("Enter 1 for Penny\nEnter 5 for Nickel\nEnter 10 for Dime\n:")
coin_amnt = raw_input("Enter amount: ")
for i in range(coin_amnt):
coins[coin_type][1].append(coins[coin_type][0]())
To check total amount of a coin type:
len(coins[coin_type][1])
To check individual instances of a coin type:
for c in coins[coin_type][1]:
print c.weight, c.height
If you wanted to print a coin's type, you can add a __str__() special method to each of your coin classes, and then print the instance as you loop the list.
Hope this helps.
Related
Create an employee class with the following members: name, age, id, salary
setData() - should allow employee data to be set via user input
getData()- should output employee data to the console
create a list of 5 employees. You can create a list of objects in the following way, appending the objects to the lists.
emp_object = []
for i in range(5):
emp_ object.append(ClassName())
I'm trying to do this exercise and this is what I got:
class employee:
def __init__(self, n = None, a = None, i = None, s = None):
self.name = n
self.age = a
self.id = i
self.salary = s
def setData(self):
self.n = input("Enter name: ")
self.a = int(input("Enter age: "))
self.i = int(input("Enter id: "))
self.s = int(input("Enter salary: "))
self.getData()
def getData(self):
print("Name:", self.name, self.age, self.id, self.salary)
e1 = employee()
e1.setData()
e2 = employee()
e2.setData()
e3 = employee()
e3.setData()
e4 = employee()
e4.setData()
e5 = employee()
e5.setData()
emp_object = []
for i in range(5):
emp_object.append(employee())
print(emp_object)
It prints the employee details as "None" and I need help to create a list
Expected Output:
Name id Age Salary
AAA 20 1 2000
BBB 22 2 2500
CCC 20 3 1500
DDD 22 4 3500
EEE 22 5 4000
Change the instance variable self.n ( in the setData method) to self.name to match the declaration your class init method ...and do the same for the self.a, self.i... variables .
I beleive the problem is that you are not setting the parameters to the ones you want in the setData function.
You need to do this:
class employee:
def __init__(self, n = None, a = None, i = None, s = None):
self.name = n
self.age = a
self.id = i
self.salary = s
def setData(self):
self.name = input("Enter name: ")
self.age = int(input("Enter age: "))
self.id = int(input("Enter id: "))
self.salary = int(input("Enter salary: "))
self.getData()
def getData(self):
print("Name:", self.name, self.age, self.id, self.salary)
The __init__ and setData are two separate functions.
First you want to separate some responsabilities for a better reading.
We will divide the problem in two parts :
Employee model
Input/output problem
Employee
Create a class who contains only employee data (we can use dataclasses but, I assume you're a beginner, so I'll keep simple)
class Employee:
def __init__(self, uid=None, name=None, age=None, salary=None):
self.name = name
self.age = age
self.id = uid
self.salary = salary
Output and Input
To display the employee's data in console, we can use __str__ function. It is used when you class need to be converted into a str (in print for isntance).
We then add an other method in charge to set employee's data.
Our Employee class become :
class Employee:
def __init__(self, uid=None, name=None, age=None, salary=None):
self.name = name
self.age = age
self.id = uid
self.salary = salary
def __str__(self):
return f"Name: {self.name}, {self.age}, {self.id}, {self.salary}"
def set_data(self):
self.name = input("Enter name: ")
self.age = int(input("Enter age: "))
self.id = int(input("Enter id: "))
self.salary = int(input("Enter salary: "))
Our class is complete. Now we will write the algorithm in charge to create 5 employees.
So under the Employee class :
if __name__ == '__main__':
# Empty list containing our employees
employees = []
# We loop 5 times.
for i in range(5):
# We create an employee
employee = Employee()
# We set the data
employee.set_data()
# We append our brand-new employee into the list
employees.append(employee)
# Now we display our data :
for employee in employees:
# We just need to print the object thanks to __str__ method
print(employee)
Tell me if I answered correctly to your problem !
I have a class I've imported into a Python file. But my code is printing the location of the object not the data stored in the object. It is giving me this output, '<Chapter_10_Program_Exercise_5.RetailItem object at 0x10e281520>' which I think is the location but how can I change that? Here's the code and a picture of the python terminal output.
class RetailItem:
# __init__ method initializes the attributes.
def __init__(self, description, units, price):
self.__item_description = description
self.__units_in_inventory = units
self.__price = price
# The set_item_description method gets the item type.
def set_item_description(self, description):
self.__item_description = description
# The set_units_in_inventory method gets number of items available.
def set_units_in_inventory(self, units):
self.__units_in_inventory = units
# The set_price method gets the cost of item.
def set_price(self, price):
self.__price = price
# The get_item_description method returns the item type.
def get_item_description(self):
return self.__item_description
# The get_units_in_inventory returns the number of items available.
def get_units_in_inventory(self):
return self.__units_in_inventory
# The get_price method returns the cost of item.
def get_price(self):
return self.__price
from Chapter_10_Program_Exercise_5 import RetailItem
class CashRegister:
# The __init__ method initializes the attributes.
def __init__(self):
self.__items = []
def clear(self):
self.__items = []
def purchase_item(self, retail_item):
self.__items.append(retail_item)
print('The item was added to the cash register.')
def get_total(self):
total_cost = 0.0
# for loop
for item in self.__items:
total_cost = total_cost +item.get_price()
return total_cost
def display_items(self):
print('The items in the cash register are:')
for item in self.__items:
print(item)
PANTS = 1
SHIRT = 2
DRESS = 3
SOCKS = 4
SWEATER = 5
def main():
pants = RetailItem('Pants', 10, 19.99)
shirt = RetailItem('Shirt', 15, 12.50)
dress = RetailItem('Dress', 3, 79.00)
socks = RetailItem('Socks', 50, 1.00)
sweater = RetailItem('Sweater', 5, 49.99)
sale_items = {PANTS:pants, SHIRT:shirt, DRESS:dress, SOCKS:socks, SWEATER:sweater}
register = CashRegister()
checkout = 'N'
while checkout =='N':
# Call the get_user_option and it is assigned to the user_option
user_option = get_user_option()
# Sale_items of argument user_option is assigned to the item
item= sale_items[user_option]
# If condition to check the items in the items_in_inventory
if item.get_units_in_inventory()== 0:
print('The item is out of stock.')
else:
register.purchase_item(item)
# New item is updated and it is assigned to the new_item
new_item = RetailItem(item.get_item_description(),
item.get_units_in_inventory()-1,
item.get_price())
# Item is updated according to the user selected option
sale_items[user_option] = new_item
# The user input is assigned to the attribute checkout
checkout = input('Are you ready to check out (Y/N)? ')
print()
print('Your purchase total is:',\
format(register.get_total(),'.2f'))
print()
register.display_items()
register.clear()
# Define the get_user_option() method to print the menu items
def get_user_option():
print('Menu')
print('-------------------')
print('1. Pants')
print('2. Shirt')
print('3. Dress')
print('4. Socks')
print('5. Sweater')
print()
option = int(input('Enter the menu number of the item you would like to purchase: '))
print()
while option > SWEATER or option < PANTS:
option = int(input('Please enter a valid item number: '))
return option
main()
Python Terminal Output
This is how python manages the printing of objects. If you want to print attributes you need to tell python which representation you want for your object.
You can do that by implementing these methods in the object class:
class RetailItem:
.
.
.
def __repr__(self):
return "RetailItem()"
def __str__(self):
return "" + self.__item_description + str(self.__units_in_inventory) + str(self.__price)
Note that the two methods will be automatically called in different situations:
>>> ri = RetailItem()
>>> ri
RetailItem()
>>> print(ri)
description 2.0 13.99
Since all variables within RetailItem are private, you'd
need to use the getter method (get_*()) to grab the info.
So to apply that to your display_items() method:
def display_items(self):
print('The items in the cash register are:')
for item in self.__items:
print("Description: %s, Units in Inventory: %d, Price: %0.2f" %
(item.get_item_description(),
item.get_units_in_inventory(),
item.get_price())
I'm a beginner at coding and tried looking up the error but could not find why it showed up. Could someone please explain it to me?
My code as follows is:
class Automobile:
__material = None
__height = None
__width = None
__engine_size = None
def set_values(self, mat, height, width, engsz="M"):
self.__material = mat
self.__height = height
self.__width = width
self.__engine_size = engsz
def getMat(self):
return self.__material
def getHeight(self):
return self.__height
def getWidth(self):
return self.__width
def getEngineSize(self):
return self.__engine_size
class Car(Automobile):
__pricePU = None
def __findPricePerUnit(self):
return priceDict[self.getMat]
def price(self):
return self.getWidth * self.getHeight * self.__findPricePerUnit
print("A new car is being made")
print("What are the dimensions wanted for the new car in")
mat = input("Enter material: ")
height = input("Enter height: ")
width = input("Enter width: ")
car1 = Car()
car1.set_values(mat, height, width)
print("A new car has been made!")
print("The price of this new car is: ")
print(car1.price)
My input for this is:
iron=10,steel=20,gold=50,diamond=100
gold
1.5
5
The OUTPUT shown at the end is:
A new car has been made!
The price of this new car is:
<bound method Car.price of <__main__.Car object at 0x0000025DE7E84C70>>
I am not exactly sure why this is coming up, could someone please explain this to me!
There are several errors in the code, some of which are as follows:
On the last line, you should execute the price function like this car1.price()
In the price function, you should execute the functions instead of multiplying the pointers of the functions, like this:
def price(self):
return self.getWidth() * self.getHeight() * self.__findPricePerUnit()
There is no priceDict, so there will be an error in __findPricePerUnit as well.
print("A new car has been made!")
print("The price of this new car is: ")
print(car1.price())
Because price() is a method.
So in python 3 I am having trouble creating multiple instances of a class automatically. I am trying to make monopoly and here is the code sample that is giving me problems.
def numplayer():
numplayer = int(input('How many players would you like? (up to four)'))
while numplayer > 4 or numplayer < 1:
numplayer = int(input('How many players would you like? (up to
four)'))
for i in range(numplayer):
PlayerMoney.append(1500)
What I want to do is also add something that will create the number of players that numplayers equals to in the for i in range(numplayer) function. I have the player as a class but I don't want to manually create every single class for every player. If there is a solution to this, please do tell. Thanks!
EDIT: So I think this might be bad wording in the title but I'm trying to create multiple instances of a single class (the player).
Here is the code for the player class:
class Player:
def __init__(self, name, money, position):
self.name = name
self.money = money
self.position = position
def DiceRoll(self):
x = random.randint(1, 6)
y = random.randint(1, 6)
sum = x + y
return [sum, x, y]
def getName(self):
return sef.name
def getMoney(self):
return self.money
def getPosition(self):
return self.position
# Create Class
class Player:
def greating(self):
print 'Hello!'
# List to store instanses
l = []
for i in range(4):
l.append(Player())
# Call Instance #1 methods
l[0].greating()
Here we have a player class and 4 instances from this class stored in l list.
I would advise you structure your code as below. It's usually a good idea for your function to return something.
def setup():
n = int(input('How many players would you like? (up to 4)'))
names = [input('Give name #{0}'.format(i)) for i in range(1, n+1)]
return [Player(name, 1500, 0) for name in names]
players = setup()
I have to call the "accelerate" method 5 times and display it's output after each iteration. The same must be done with the "brake" method. I have all of this written, but I'm at a loss in where to even begin to call the method in the main function to achieve my desired goal. Any help is greatly appreciated!! I'm in Python 3.3
class Car:
def __init__(self):
self.__year_model = 0
self.__make = ''
self.__speed = 0
def set_year_model(self, year):
self.__year_model = year
def set_make(self, make):
self.__make = make
def set_speed(self, speed):
self.__speed = speed
def accelerate(self):
return self.__speed + 5
def brake(self):
return self.__speed - 5
def get_year_model(self):
return self.__year_model
def get_make(self):
return self.__make
def get_speed(self):
return self.__speed
def main():
mycar = Car()
year = input('Enter the year of the vehicle: ')
make = input('Enter the make of the vehicle: ')
speed = input("Enter the vehicle's current speed: ")
mycar.set_year_model(year)
mycar.set_make(make)
mycar.set_speed(speed)
accel = mycar.accelerate()
brake = mycar.brake()
main()
Your accelerate code is wrong: the changed speed is never stored. It should be
def accelerate(self):
self.__speed += 5
and similarly for brake.
Edit: getter and setter methods aren't really idiomatic Python. You probably want
class Car:
def __init__(self, year, make, speed=0):
self.year = year
self.make = make
self.speed = speed
def accelerate(self, amount=5):
self.speed += amount
def brake(self, amount=5):
self.speed -= amount
def main():
year = input('Enter the year of the vehicle: ')
make = input('Enter the make of the vehicle: ')
speed = input("Enter the vehicle's current speed: ")
mycar = Car(year, make, int(speed))
print("Accelerating:")
for _ in range(5):
mycar.accelerate()
print(mycar.speed)
print("Braking:")
for _ in range(5):
mycar.brake()
print(mycar.speed)
if __name__=="__main__":
main()
which gives
Enter the year of the vehicle: 1990
Enter the make of the vehicle: Corolla
Enter the vehicle's current speed: 20
Accelerating:
25
30
35
40
45
Braking:
40
35
30
25
20
This would be solved by a simple looping structure. In your main method, try:
for item in range(0,5):
accel = mycar.accelerate()
print(accel)
Edit: Please note that this is probably not the best way to do this, but the first way that came to mind. In regards to the int/str conversion, you might just want to cast. I typically use Python 2.7.x and couldn't remember if you needed to cast to string for Python 3.0's print function.