iterating objects in a list through a loop - python

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)

Related

How do I get the max speed from the Objects? And is their any way to make this code more efficient?

I am new to python, here i created a class to calculate speed, now i just need a way to find the max speed from the objects.
class CarSpeed:
def __init__(self,name,dist,time):
self.dist=dist
self.time=time
self.name=name
def ans(self):
speed= self.dist/self.time
print(self.name,"_Speed ""(",self.dist,"/",self.time,"):",speed,"\n")
Ford=CarSpeed("Ford",120,1.75)
Ford.ans()
Ferrari=CarSpeed("Ferrari",100,1.20)
Ferrari.ans()
BMW=CarSpeed("BMW",205,2.35)
BMW.ans()
Porsche=CarSpeed("Porsche",155,1.85)
Porsche.ans()
Audi=CarSpeed("Audi",190,2.10)
Audi.ans()
Jaguar=CarSpeed("Jaguar",255,2.45)
Jaguar.ans()
I need the output in this way:
The car with the highest speed is: CAR BRAND
You can do it using max function
You can also change your speed to self.speed and add it without value to init
class CarSpeed():
def __init__(self,name,dist,time):
self.dist=dist
self.time=time
self.name=name
self.speed = None
def ans(self):
self.speed = self.dist/self.time
print(self.name,"_Speed ""(",self.dist,"/",self.time,"):",self.speed,"\n")
then you can calculate it without calling this function but from class directly by replacing self.speed = None by self.speed = self.ans()
so full code will look like this
class CarSpeed:
def __init__(self, name, dist, time):
self.dist = dist
self.time = time
self.name = name
self.speed = self.ans()
def ans(self):
self.speed = self.dist/self.time
return self.speed
speed_list = {}
Ford = CarSpeed("Ford", 120, 1.75)
speed_list.update({Ford.name: Ford.speed})
Ferrari = CarSpeed("Ferrari", 100, 1.20)
speed_list.update({Ferrari.name: Ferrari.speed})
BMW = CarSpeed("BMW", 205, 2.35)
speed_list.update({BMW.name: BMW.speed})
Porsche = CarSpeed("Porsche", 155, 1.85)
speed_list.update({Porsche.name: Porsche.speed})
Audi = CarSpeed("Audi", 190, 2.10)
speed_list.update({Audi.name: Audi.speed})
Jaguar = CarSpeed("Jaguar", 255, 2.45)
speed_list.update({Jaguar.name: Jaguar.speed})
fastest = max(speed_list, key=speed_list.get)
print(f"{fastest} is the fastest car")
Try this
class CarSpeed:
def __init__(self,name,dist,time):
self.dist=dist
self.time=time
self.name=name
def ans(self):
speed= self.dist/self.time
return speed
speed_list = {}
Ford=CarSpeed("Ford",120,1.75)
speed_list.update({Ford.name: Ford.ans()})
Ferrari=CarSpeed("Ferrari",100,1.20)
speed_list.update({Ferrari.name: Ferrari.ans()})
BMW=CarSpeed("BMW",205,2.35)
speed_list.update({BMW.name: BMW.ans()})
Porsche=CarSpeed("Porsche",155,1.85)
speed_list.update({Porsche.name: Porsche.ans()})
Audi=CarSpeed("Audi",190,2.10)
speed_list.update({Audi.name: Audi.ans()})
Jaguar=CarSpeed("Jaguar",255,2.45)
speed_list.update({Jaguar.name: Jaguar.ans()})
print(dict([max(speed_list)]))
You can do something like this:
class CarSpeed:
def __init__(self,name,dist,time):
self.dist=dist
self.time=time
self.name=name
#property
def ans(self):
speed = self.dist/self.time
return speed
cars = []
cars.append(CarSpeed("Ford",120,1.75))
cars.append(CarSpeed("Ferrari",100,1.20))
cars.append(CarSpeed("BMW",205,2.35))
cars.append(CarSpeed("Porsche",155,1.85))
cars.append(CarSpeed("Audi",190,2.10))
cars.append(CarSpeed("Jaguar",255,2.45))
fastest = max(cars, key=lambda x: x.ans)
print('The car with the highest speed is: ,'fastest.name, fastest.ans)
The output will be:
The car with the highest speed is Jaguar 104.08163265306122

Checking if contained object has changed

I am working on creating a module with a class that acts as a container for a list of another created class. Is there a way for the container class to be able to tell if any of the objects it contains has changed?
Here is an example:
class Part:
def __init__(self, size):
self.part_size = size
class Assembly:
def __init__(self, *parts):
self.parts = list(parts) # `parts` are all Part() objects
self.update()
def update(self):
self.assy_size = 0
for each in self.parts:
self.assy_size += each.part_size
def __getitem__(self, key):
return self.parts[key]
This is what I get if I try to change any of the Part properties in the Assembly:
>>>x = Part(1)
>>>y = Part(1)
>>>z = Part(1)
>>>u = Assembly(x, y, z)
>>>u.assy_size
3
>>>u[0].part_size = 4
>>>u.assy_size
3
I know that I can create additional methods that will call the update method if I replace, delete, or add Part objects to the Assembly, but is there any way to have the Assembly notified if any of the contained Part properties have changed?
The answer is in your question. Use a property.
class Part:
_size = 0
assembly = None
#property
def part_size(self):
return self._size
#part_size.setter
def part_size(self, value):
self._size = value
if self.assembly: # only notify if an Assembly is set
self.assembly.update()
def set_assembly(self, assembly):
self.assembly = assembly
def __init__(self, size):
self.part_size = size
class Assembly:
def __init__(self, *parts):
self.parts = list(parts) # `parts` are all Part() objects
for part in self.parts:
part.set_assembly(self) # reference to self needed to notify changes
self.update()
def update(self):
self.assy_size = 0
for each in self.parts:
self.assy_size += each.part_size
In this version of Assembly the constructor sets a reference on the Part to itself. This way it can update the assembly when the part_size changes. Use it as the example in your question.
>>>x = Part(1)
>>>y = Part(1)
>>>z = Part(1)
>>>u = Assembly(x, y, z)
>>>u.assy_size
3
>>>u[0].part_size = 4
>>>u.assy_size
6
If update isn't an expensive operation (in your example it isn't, but maybe in reality you have thousands of parts), you could calculate the size ad-hoc using a property:
class Assembly:
def __init__(self, *parts):
self.parts = list(parts)
#property
def assy_size(self):
result = 0
for each in self.parts:
result += each.part_size
return result
which can be accessed the same way: assembly.assy_size.
The calculation can also be simplified:
#property
def assy_size(self):
return sum(part.part_size for part in self.parts)

Unable to run a simple python program

I started learning python. Here is a simple program:
class StudentRepo:
def __init__(self):
self.student_list = []
def add(self, student):
self.student_list.append(student)
def get_list(self):
self.student_list
class Student:
def __init__(self, name, age):
self.age = age
self.name = name
from models.student.Student import Student
from services.student.StudentRepo import StudentRepo
s1 = Student("A", 10)
s2 = Student("B", 11)
# What is the issue here ?
StudentRepo.add(s1)
StudentRepo.add(s2)
studentList = StudentRepo.get_list()
for student in studentList:
print(student.name)
What is the issue with s1 = Student("A", 10) ?
There are two mistakes in your code. First, this:
def get_list(self):
self.student_list
should be:
def get_list(self):
return self.student_list
Second, you're using the class StudentRepo where you should be using an instance of StudentRepo:
s1 = Student("A", 10)
s2 = Student("B", 11)
my_roster = StudentRepo()
my_roster.add(s1)
my_roster.add(s2)
studentList = my_roster.get_list()
for student in studentList:
print(student.name)

Competition registration program using classes

I have an assignment to create a code that would define 2 classes, a player and a team each of these having some parameters. Player is supposed to have a name, a number of skis, a number of sledges and a player index(number of games played by the player before).
I managed to define these attributes of the class but I'm having a hard time implementing the team class. Team is supposed to hold the name of the team and the number of players-the players cannot be just their names it must link to the class instance(player). I don't understand how to use the information provided in the player instance to implement team. Here's my code so far:
class Player:
def __init__(self, name, skis, index):
self.name = name
self.sledges = []
self.skis = []
self.index = index
pass
class Team:
def __init__(self, name, players):
self.name = name
self.players = [Player]
pass
def get_players_count()
def get_transport_capacity()
def get_average_index()
*Update
Thank you for your help, I have one more function to add, a function that would return the number of passengers a team could accommodate. I've tried something like this but I don't think the syntax is correct. The user inputs the number of places in each sledge so I need to iterate over the values in the list to get the number of places.
def get_transport_capacity(self):
skis = len(Player.skis)
for i in Player.sledges:
sledges += Player.sledges[i]
capacity = skis + sledges
return capacity
class Player:
def __init__(self, name, index):
self.name = name
self.sledges = []
self.skis = []
self.index = index
class Team:
def __init__(self, name, players):
self.name = name
self.players = players
def get_players_count(self):
return len(self.players)
def add_player(self, player):
self.players.append(player)
def get_average_index(self):
indexes = sum(list(map(lambda p: p.index, self.players)))
count = self.get_players_count()
return float(indexes) / count
Usage:
a = Player('AName', 2)
b = Player('BName', 11)
team = Team('TeamName', [a, b])
instead of
self.players = [Player]
why not:
self.players = []
And then have a method to add players to the team as in:
def add_player(self, player):
# ensure optionally that player is a PLayer instance
assert type(player) == Player
self.players += player

builtins.TypeError: __init__() missing 2 required positional arguments:

My Code:
class SUCHER(EventHandler):
def __init__(self):
self.vokabel = VOKABEL()
EventHandler.__init__(self)
self.button = Button("Suchen!", Point(250,200))
self.button.setFontSize(25)
self.button.setFillColor("lightgrey")
self.button.addHandler(self)
self.lateinischesWort = TextBox(200,50,Point(120,100))
self.übersetzungsText = Rectangle(200,50,Point(380,100))
self.textD = Text("Deutsches Wort", 15, Point(380,50))
self.textL = Text("Lateinisches Wort", 15, Point(120,50))
self.textU = Text(self.vokabel, 25, Point(380,100))
def anzeigenIn(self, Fenster):
Fenster.add(self.button)
Fenster.add(self.übersetzungsText)
Fenster.add(self.lateinischesWort)
Fenster.add(self.textD)
Fenster.add(self.textL)
Fenster.add(self.textU)
def handle(self, Event):
if Event.getDescription() == "mouse click":
self.textL = self.wort
self.textU = self.übersetzung
self.textU.setMessage(self.vokabel)
class BINÄRBAUM:
def __init__(self):
self.wurzel = ABSCHLUSS()
def einfügen(self, Datum):
self.wurzel = self.wurzel.einfügen(Datum)
def inorderAusgeben(self):
self.wurzel.inorderAusgeben()
def preorderAusgeben(self):
self.wurzel.preorderAusgeben()
def postorderAusgeben(self):
self.wurzel.postorderAusgeben()
def suchen(self, Schlüssel):
self.wurzel.suchen(Schlüssel)
class KNOTEN:
def __init__(self, Datum):
self.datum = Datum
self.links = ABSCHLUSS()
self.rechts = ABSCHLUSS()
def einfügen(self, Datum):
if Datum.schlüsselGeben() < self.datum.schlüsselGeben():
self.links = self.links.einfügen(Datum)
else:
self.rechts = self.rechts.einfügen(Datum)
return self
def inorderAusgeben(self):
self.links.inorderAusgeben()
self.datum.informationAusgeben()
self.rechts.inorderAusgeben()
def preorderAusgeben(self):
self.datum.informationAusgeben()
self.links.preorderAusgeben()
self.rechts.preorderAusgeben()
def postorderAusgeben(self):
self.links.postorderAusgeben()
self.rechts.postorderAusgeben()
self.datum.informationAusgeben()
def suchen(self, Schlüssel):
if self.datum.schlüsselGeben() == Schlüssel.casefold():
self.datum.informationAusgeben()
elif self.datum.schlüsselGeben() > Schlüssel.casefold():
self.links.suchen(Schlüssel)
else:
self.rechts.suchen(Schlüssel)
class ABSCHLUSS:
def __init__(self):
pass
def einfügen(self, Datum):
return KNOTEN(Datum)
def inorderAusgeben(self):
pass
def preorderAusgeben(self):
pass
def postorderAusgeben(self):
pass
def suchen(self, Schlüssel):
pass
class VOKABEL:
def __init__(self, Wort, Übersetzung):
self.wort = Wort
self.übersetzung = Übersetzung
def informationAusgeben(self):
print("Das Wort",self.wort,"hat die Bedeutung",self.übersetzung,".")
def schlüsselGeben(self):
return self.wort.casefold()
v = VOKABEL("Nebel", "fog")
s = SUCHER()
b = BINÄRBAUM()
b.einfügen(v)
b.inorderAusgeben()
b.preorderAusgeben()
b.postorderAusgeben()
b.suchen("Nebel")
fenster = Canvas(500,250)
s.anzeigenIn(fenster)
I'm a programmer from Germany and I have a problem.By the way I use the module cs1graphics. I get the Error : builtins.TypeError: init() missing 2 required positional arguments: 'Wort' and 'Übersetzung'
so what can I do to solve this?
class SUCHER(EventHandler):
def __init__(self):
self.vokabel = VOKABEL()
You are instanciating a new VOKABEL class without giving it the 2 arguments it needs. See here the constructor :
class VOKABEL:
def __init__(self, Wort, Übersetzung):

Categories

Resources