I am creating a python activity and I am wondering how setting the parameter of my method as a data type work
my code is:
class Food:
def __init__(self, weight: int, energy_add: int, happiness_add: int):
self.weight = weight # in kg
self.energy_add = energy_add
self.happiness_add = happiness_add
class Student:
def __init__(self, student_number: int, name: str, weight: float):
self.student_number = student_number
self.name = name
self.weight = weight # in kg
def eat(self,food = Food(int, int, int)):
self.weight = food.weight
class EEE111Student(Student):
energy_level = 50
happiness_level = 50
def eat(self,food = Food(int, int, int)):
print(self.weight)
self.weight += food.weight
print(food.weight)
print(self.weight)
if __name__ == "__main__":
num_students = int(input("Enter the number of students: "))
students = []
for idx in range(num_students):
# TODO: create new_student here
new_student = EEE111Student(student_number=idx, name=f"Student{idx}", weight=(50 + (0.5 * (idx -1))) )
students.append(new_student)
food_choises = {
"papaya" : Food(weight=0.10, energy_add=10, happiness_add=5),
"corn": Food(weight=0.20, energy_add=5, happiness_add=6),
}
students[0].eat(food = food_choises["papaya"])
students[0].eat(food = food_choises["corn"])
I am grateful that it works because i tried setting the parameter for EEE111's eat method as :
def eat(self,food = Food(Food.weight, Food.energy_add, Food.happiness_add)):
print(self.weight)
self.weight += food.weight
print(food.weight)
print(self.weight)
I am wondering if this might be a basic structure for a python code
You're never calling eat() without an parameter, so you don't need a default Food value being passed.
Instead, you can just define the type
def eat(self, food: Food)
Related
A very simple problem, yet I need some assistance. I have created a class that has some default values. After that an instance takes the values based on an input. If one of the properties is "null" how can I assign the default value to it?
class Dragon:
dragons=[]
def __init__(self,dragon_type,name,health=2000,attack=450,fly_speed=120):
self.dragon_type=dragon_type
self.name=name
self.health=health
self.attack=attack
self.fly_speed=fly_speed
Dragon.dragons.append(self)
num=int(input())
for n in range(num):
entry=input().split() #fire Azzaaxx null 480 null
dragon_type,name,health,attack,fly_speed=entry[0],entry[1],entry[2],entry[3],entry[4]
if health=="null":
health=... #2000
else:
health=int(health)
if attack=="null":
attack=... #450
else:
attack=int(attack)
if fly_speed=="null":
fly_speed=... #120
else:
fly_speed=int(fly_speed)
obj=Dragon(dragon_type,name,health,attack,fly_speed)
Is this approach acceptable or this should be defined differently?
Thank you in advance!
Change the class definition so that None values are converted to the default.
class Dragon:
dragons=[]
def __init__(self,dragon_type,name,health=None,attack=None,fly_speed=None):
self.dragon_type=dragon_type
self.name=name
self.health=health if health is not None else 2000
self.attack=attack if attack is not None else 450
self.fly_speed=fly_speed if fly_speed is not None else 120
Dragon.dragons.append(self)
Then you can set the variables in the caller to None if the user enters null, and the __init__() method will do the right thing, so you don't have to repeat the default values.
Build up a dictionary of non-null values to use as keyword arguments.
args = {}
if health != "null":
args['health'] = int(health)
if attack != "null":
args['attack'] = int(attack)
if fly_speed != "null":
args['fly_speed'] = int(fly_speed)
obj = Dragon(dragon_type, name, **args)
However, this is a good opportunity to move the handling of "missing" values to a class method. __init__ should require values; the class method will provide defaults when its own input is lacking.
class Dragon:
dragons = []
def __init__(self, dragon_type, name, health: int, attack: int, fly_speed: int):
self.dragon_type = dragon_type
self.name = name
self.health = health
self.attack = attack
self.fly_speed = fly_speed
Dragon.dragons.append(self)
#classmethod
def from_input(cls):
entry = input().split()
health = int(entry[2]) if entry[2] != "null" else 2000
attack = int(entry[3]) if entry[3] != "null" else 450
speed = int(entry[4]) if entry[4] != "null" else 120
return cls(entry[0], entry[1], health, attack, speed)
num = int(input())
for n in range(num):
obj = Dragon.from_input()
So I'm just doing a learning project and I need some help.
class Car:
def __init__(self):
self.speed = 0
self.color = ""
self.weight = 0
self.engine = 4
self.name = ""
self.mpg = 25
self.maintenanceLog = []
self.oilChanges = []
#mutator methods
def setSpeed(self, sp):
self.speed = sp
def setColor(self, cl):
self.color = cl
def setWeight(self, w):
self.weight = w
def setEngine(self, e):
self.engine = e
def setName(self, n):
self.name = n
def setMpg(self, mpg):
self.mpg = mpg
def addOilChange(self, oc):
self.oilChanges.append(oc)
def addMaintenance(self, ml):
self.maintenanceLog.append(ml)
#accessor methods
def getSpeed(self):
return self.speed
def getColor(self):
return self.color
def getWeight(self):
return self.weight
def getEngine(self):
return self.engine
def getName(self):
return self.name
def getMPG(self):
return self.mpg
def getAllOilChanges(self):
print("")
print("----------OIL CHANGES----------")
for oc in self.oilChanges:
print(oc)
def getMaintenanceLogs(self):
print("")
print("----------MAINTENANCE LOGS----------")
for ml in self.maintenanceLog:
print(ml)
def setInfo(car):
car.setSpeed(int(input(f"Speed of {car}")))
car.setWeight(int(input(f"Weight of {car}")))
car.setName(input(f"Name of {car}"))
car.setColor(input(f"Color of {car}"))
car.setEngine(int(input(f"Engine of {car}")))
car.setMpg(int(input(f"Miles per Gallon of {car}")))
def getInfo(car):
print(f"Speed of {car} is {car.getSpeed()} mph.")
print(f"Weight of {car} is {car.getWeight()} pounds.")
print(f"Name of {car} is {car.getName()}.")
print(f"Color of {car} is {car.getColor()}.")
print(f"Engine cylinders of {car} are {car.getEngine()}.")
print(f"Miles per Gallon of {car} is {car.getMPG()}.")
def main():
carList = []
Object1= Car()
carList.append(Object1)
print(carList)
for obj in carList:
setInfo(obj)
getInfo(obj)
main()
Thats's the code, now, whenever I run it, I want to get asked Speed of Object1:
Instead, I get asked Speed of <main.Car object at 0x0000024B093CEFD0>:
How can I see the name of the object instead of that hash value... I want to keep adding objects with the class Car and then pass them through a loop to fill in the information regarding the object, but if the list of objects was [Object 1, Object 2, Object 3... Object N] I want it to refer to that name (Object 1) instead of <main.Car object at 0x0000024B093CEFD0>
You can pass the name to use in the prompts as an argument to setInfo().
def setInfo(car, name=None):
if name is None:
name = car.name
car.setSpeed(int(input(f"Speed of {name}")))
car.setWeight(int(input(f"Weight of {name}")))
car.setName(input(f"Name of {name}"))
car.setColor(input(f"Color of {name}"))
car.setEngine(int(input(f"Engine of {name}")))
car.setMpg(int(input(f"Miles per Gallon of {name}")))
and then use that in the loop.
for i, obj in enumerate(carList, 1):
setInfo(obj, f"Object {i}")
getInfo(obj)
I have a class name Student like this:
class Student:
def __init__(self, name = '', age = 0, test_score = 0):
self.name = name
self.age = age
self.test_Scores = test_score
def __str__(self):
return "({0},{1},{2})".format(self.name,self.age, self.test_Scores)
and class name Students:
class Students():
stds = list()
def __init__(self) -> None:
pass
def Input(self):
while True:
inputName = input('Enter name: ')
inputAge = int(input('Enter age: '))
inputTestScore = int(input('Enter test score: '))
std = Student(inputName, inputAge, inputTestScore)
if inputAge == 0:
break
self.stds.append(std)
def __str__(self):
return str(self.stds)
Here are some code print out a list of students:
stds = Students()
stds.Input()
print(stds)
With 2 elements in the list, the result after excute look like this:
[<main.Student object at 0x0000026EDEBC5FA0>, <main.Student object at 0x0000026EDEBC5CD0>]
I can't print out stds under a string, how can i fix it. And how to sort stds by the decreasing of age ?
Pls help me !
You shouldn't have class Students, you should have a list of Student. To get the data from the class variables override the __repr__ method. To sort the list you can use lambda with the attribute to sort by as key in sort() function
class Student:
def __init__(self, name='', age=0, test_score=0):
self.name = name
self.age = age
self.test_Scores = test_score
def __repr__(self):
return "({0},{1},{2})".format(self.name, self.age, self.test_Scores)
if __name__ == '__main__':
stds = list()
while True:
inputName = input('Enter name: ')
inputAge = int(input('Enter age: '))
inputTestScore = int(input('Enter test score: '))
std = Student(inputName, inputAge, inputTestScore)
if inputAge == 0:
break
stds.append(std)
stds.sort(key=lambda s: s.name)
print(stds)
You need to write the function str for students class.
def __str__(self):
return '\n'.join(self.stds)
try this =>
class Student:
def __init__(self, name = '', age = 0, test_score = 0):
self.name = name
self.age = age
self.test_Scores = test_score
def __str__(self):
return "({0},{1},{2})".format(self.name,self.age, self.test_Scores)
def __repr__(self):
return "({0},{1},{2})".format(self.name,self.age, self.test_Scores)
def __lt__(self, other):
return self.age < other.age
class Students():
stds = list()
def __init__(self) -> None:
pass
def Input(self):
while True:
inputName = input('Enter name: ')
inputAge = int(input('Enter age: '))
inputTestScore = int(input('Enter test score: '))
std = Student(inputName, inputAge, inputTestScore)
if inputAge == 0:
break
self.stds.append(std)
def __str__(self):
return str(self.stds)
stds = Students()
stds.Input()
print(stds)
stds.stds.sort(reverse=True)
print(stds)
Define a natural order for the students based on their age using #functools.total_ordering:
import functools
#functools.total_ordering
class Student:
def __init__(self, name='', age=0, test_score=0):
self.name = name
self.age = age
self.test_Scores = test_score
def __lt__(self, other):
return self.age < other.age
def __str__(self):
return "({0},{1},{2})".format(self.name, self.age, self.test_Scores)
def test_sorting_students():
alice: Student = Student("Alice", 21, 86)
bob: Student = Student("Bob", 19, 75)
caroline: Student = Student("Caroline", 20, 93)
students = [alice, bob, caroline]
students.sort()
assert students[0] == bob
assert students[1] == caroline
assert students[2] == alice
Then just sort them:
print(stds.sort())
I have to set the total_cost variable to be equal to the subtotal variable or the from the product class. However, when I try to derive the value from the class. It gives me an attribute error of AttributeError: 'Product' object has no attribute '_Product__total_price'. I am implementing where you apply the promo code then it will deduct the total price from the cart.
This is init.py and functions used.
#app.route('/applyPromo/<string:id>/', methods=['GET','POST'])
def apply_promo(id):
promotions_dict = {}
db = shelve.open('promotions.db','w')
promotions_dict = db['Promotions']
total_cost = 100
hidden = True
applied = True
click = True
get_from_class = False
print(promotions_dict)
promotions = promotions_dict.get(UUID(id))
db = shelve.open('storage.db', 'r')
product_dict = db['products']
for key in product_dict:
product = product_dict[key]
total_cost = product.get_total_price()
print(total_cost)
#when user apply promo, promo will get deleted from the list/dictionary of promos they have.
if promotions["type"] == 1:
total_cost = total_cost - 10
hidden = False
print(f"Total Cost : {total_cost}")
promotions_dict.pop(UUID(id))
elif promotions["type"] == 2:
total_cost = total_cost - 5
hidden = False
print(f"Total Cost : {total_cost}")
promotions_dict.pop(UUID(id))
elif promotions["type"] == 3:
total_cost = (70/100)*total_cost
hidden = False
print(f"Total Cost : {total_cost}")
promotions_dict.pop(UUID(id))
elif promotions["type"] == 4:
total_cost = (80/100)*total_cost
hidden = False
print(f"Total Cost : {total_cost}")
promotions_dict.pop(UUID(id))
elif promotions["type"] == 5:
total_cost = (85/100)*total_cost
hidden = False
print(f"Total Cost : {total_cost}")
promotions_dict.pop(UUID(id))
else:
total_cost = (90/100)*total_cost
hidden = False
print(f"Total Cost : {total_cost}")
promotions_dict.pop(UUID(id))
db['Promotions'] = promotions_dict
db.close()
db.close()
print(promotions_dict)
session['promotion_applied'] = promotions["id"]
return render_template("generatePromo.html", total_cost=total_cost,applied=applied, promotions_dict=promotions_dict,hidden=hidden,promotions=promotions,get_from_class=get_from_class, click=click)
#app.route('/shopping_cart')
def shopping_cart():
# session.clear()
error = None
cart_items = []
quantity_list = []
subtotal = 0
db = shelve.open('storage.db', 'r')
product_dict = db['products']
db.close()
for products in session:
item = product_dict.get(products)
cart_items.append(item)
if None in cart_items:
cart_items.remove(None)
quantity_list.append(session[products])
if products in quantity_list:
quantity_list.remove(products)
for i in range(len(cart_items)):
cart_items[i].set_purchased_quantity(quantity_list[i])
# set total price for single item
item_total = int(cart_items[i].get_price()) * int(cart_items[i].get_purchased_quantity())
cart_items[i].set_total_price(item_total)
# set total price of all items in cart
subtotal += item_total
print('QTY LIST', quantity_list)
print('CART', cart_items)
if not cart_items:
error = "Cart Is Empty"
return render_template('shoppingcart.html', products_list=cart_items, error=error, subtotal=subtotal)
This is the product class.
from uuid import uuid4
class Product:
def __init__(self, name, price, quantity, color, vase, remarks):
self.__product__id = str(uuid4())
self.__name = name
self.__price = price
self.__quantity = quantity
self.__color = color
self.__vase = vase
self.__remarks = remarks
self.__purchased_quantity = 0
self.__total_price = 0
def get_product_id(self):
return self.__product__id
def get_name(self):
return self.__name
def get_price(self):
return self.__price
def get_quantity(self):
return self.__quantity
def get_color(self):
return self.__color
def get_vase(self):
return self.__vase
def get_remarks(self):
return self.__remarks
def get_image(self):
return self.__image
def get_purchased_quantity(self):
return self.__purchased_quantity
def get_total_price(self):
return self.__total_price
def set_name(self, name):
self.__name = name
def set_price(self, price):
self.__price = price
def set_quantity(self, quantity):
self.__quantity = quantity
def set_color(self, color):
self.__color = color
def set_vase(self, vase):
self.__vase = vase
def set_remarks(self, remarks):
self.__remarks = remarks
def set_image(self, image):
self.__image = image
def set_purchased_quantity(self, purchased_quantity):
self.__purchased_quantity = purchased_quantity
def set_total_price(self, total_price):
self.__total_price = total_price
This is the traceback for the error.
Traceback
Leading double underscores should not be used as you are using them to define attributes of your class - single underscores is conventional. The problem with using leading double underscores is that the interpreter "mangles" the names of those attributes to avoid a subtle problem with inheritance, but leading to the problem, I believe, you are seeing. Here is a good read on the subject.
I have a problem. Like that!
code:
class Pass:
def __init__(self, model, color, year, position):
self.model = model
self.color = color
self.year = year
self.position = position
class Car(Pass):
def __init__(self, model, year, position):
super().__init__(model, year, position)
if self.model == "Lacetti":
self.cost = 138000000 - ((2020 - year) * 5000000)
elif self.model == "Spark":
self.cost = 92821000 - ((2020 - year) * 2000000)
elif self.model == "Malibu":
self.cost = 311124067 - ((2020 - year) * 3000000)
else:
print("Find out the price of the car on the Internet!")
def malumot(self):
return "Model: {} Color: {} Year: {} Position: {} Cost: {}".format(
self.model, self.year, self.position, self.cost
)
class Full_data(Pass):
def __init__(self, rusumi, rangi, yili, pozitsiya, carclass):
super().__init__(rusumi, rangi, yili, pozitsiya)
if self.model == "Lacetti":
self.cost = 138000000 - ((2020 - year) * 5000000)
elif self.model == "Spark":
self.cost = 92821000 - ((2020 - year) * 2000000)
elif self.model == "Malibu":
self.cost = 311124067 - ((2020 - year) * 3000000)
else:
print("Find out the price of the car on the Internet!")
self.classes = carclass
def data(self):
return "Model: {} Color: {} Year: {} Position: {} Cost: {}".format(
self.model, self.year, self.position, self.cost
)
car_1 = Car("Lacetti", 2018, "3")
print(car_1.model)
print(car_1.year)
print(car_1.position)
print(car_1.cost)
a = car_1.data()
print(a)
can you help me?
it says: "init() missing 1 required positional argument: 'position'"
I don't know what is wrong?
Can you give the answer?
Please edit wrong and send it with code!
Thank you!
You've inherited Pass class in Car class and call its init method but you need to send 4 args to Pass class (model, color, year, position) because you haven't defined any of them with a default value. However, in your Car Class, you send only 3 values (args), super().__init__(model, year, position) . You forgot to send color and python assumes you send position argument in Car Class to Pass Class as its color parameter. Respect to
Car.model = Pass.model
Car.year = Pass.year
Car.position = Pass.color
Car.?? = Pass.position
class Pass:
def __init__(self, model, color, year, position):
self.model = model
self.color = color
self.year = year
self.position = position
class Car(Pass):
def __init__(self, model, year, position):
super().__init__(model, year, position)