Passing arguments through a class in python - python

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.

Related

Python Inheritance error (with private variables)

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.

class and defining __str__

This is the exercise:
Write the special method __str__() for CarRecord.
Sample output with input: 2009 'ABC321'
Year: 2009, VIN: ABC321
The following code is what I have came up with, but I'm receiving an error:
TYPEERROR: __str__ returned non-string
I can't figure out where I went wrong.
class CarRecord:
def __init__(self):
self.year_made = 0
self.car_vin = ''
def __str__(self):
return "Year:", (my_car.year_made), "VIN:", (my_car.car_vin)
my_car = CarRecord()
my_car.year_made = int(input())
my_car.car_vin = input()
print(my_car)
You're returning a tuple using all those commas. You should also be using self, rather than my_car, while inside the class. Try like this:
def __str__(self):
return f"Year: {self.year_made}, VIN: {self.car_vin}"
The f before the string tells Python to replace any code in braces inside the string with the result of that code.
class Car:
def __init__(self):
self.model_year = 0
self.purchase_price = 0
self.current_value = 0
def print_info():
print('Car Info') # It specifies a print_info class method but doesnt actually need to print anything useful.
def calc_current_value(self, current_year):
depreciation_rate = 0.15
car_age = current_year - self.model_year
self.current_value = round(self.purchase_price * (1 - depreciation_rate) ** car_age)
def print_info(self):
print("Car's information:")
print(" Model year:", self.model_year)
print(" Purchase price:", self.purchase_price)
print(" Current value:", self.current_value)
if __name__ == "__main__":
year = int(input())
price = int(input())
current_year = int(input())
my_car = Car()
my_car.model_year = year
my_car.purchase_price = price
my_car.calc_current_value(current_year)
my_car.print_info()
def __str__(self):
return "Year: {}, VIN: {}".format(self.year_made, self.car_vin)
The trick here is that you pull values from the top of the class as they are set later in the code.
This answer works for grading
def __str__(self):
return f"Year: {}, VIN: {}".format(self.year_made, self.car_vin)`
This is easier to understand
def __str__(self):
f"Year: {self.year_made}, VIN: {self.car_vin}")

I have a bad input error in python, any ideas how to fix it?

I have this bad error in put for a game I'm trying to code. It's bare bones at the moment, and I'm trying to code the information for one of the enemies the player fights.
class Enemy():
def __init__(self):
super(). __init__ (
self.name = "Goblin" +
self.healthpoints = 12 + # on this line
self.damage = 3)
def isAlive(self):
return self.hp > 0
Do you mean to do this?
class Enemy():
def __init__(self):
self.name = "Goblin"
self.healthpoints = 12
self.damage = 3
super().__init__(name=self.name, healthpoints=self.healthpoints, damage=self.damage)
enter code here
def isAlive(self):
return self.hp > 0
```
self.name = "Goblin" + is a syntax error. You aren't adding anything to "Goblin". The reason it is complaining about the line after is that it is trying to add self.healthpoints = 12 to "Goblin" and you can't add assignment statements.
I think what you want to do is something like this:
def __init__(self):
self.name = "Goblin"
self.healthpoints = 12
self.damage = 3

How to get rid of eval in subclass appending to superclass instance list?

I am using eval to run a generated string to append the newly created EggOrder instance to the list of the correct instance of the DailyOrders class. The day provided by EggOrder is used to used to append to the correct instance. This relies on eval and the variable name of the DailyOrders instance and so it would be great to get this removed. I know there must be a better way.
class DailyOrders:
PRICE_PER_DOZEN = 6.5
def __init__(self, day):
self.orders = []
self.day = day
def total_eggs(self):
total_eggs = 0
for order in self.orders:
total_eggs += order.eggs
return total_eggs
def show_report(self):
if self.total_eggs() < 0:
print("No Orders")
else:
print(f"Summary:\nTotal Eggs Ordered: {self.total_eggs()}")
print(f"Average Eggs Per Customer: {self.total_eggs() / len(self.orders):.0f}\n*********")
class EggOrder():
def __init__(self, eggs=0, name="", day=""):
if not name:
self.new_order()
else:
self.name = name
self.eggs = eggs
self.day = day
eval(f"{self.day.lower()}.orders.append(self)")
def new_order(self):
self.name = string_checker("Name: ")
self.eggs = num_checker("Number of Eggs: ")
self.day = string_checker("Date: ")
def get_dozens(self):
if self.eggs % 12 != 0:
dozens = int(math.ceil(self.eggs / 12))
else:
dozens = self.eggs / 12
return dozens
def show_order(self):
print(f"{self.name} ordered {self.eggs} eggs. The price is ${self.get_dozens() * DailyOrders.PRICE_PER_DOZEN}.")
if __name__ == "__main__":
friday = DailyOrders("Friday")
friday_order = EggOrder(12, "Someone", "Friday")
friday_order.show_order()
friday.show_report()
saturday = DailyOrders("Saturday")
saturday_order = EggOrder(19, "Something", "Saturday")
saturday_order = EggOrder(27, "Alex Stiles", "Saturday")
saturday.show_report()
DailyOrders isn't actually a superclass (it was in a earlier version), it acts like one and I suspect the answer might have some inheritance.

I have created class need help associating the class for values

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.

Categories

Resources