Search code examples
pythonlistclassobjectoop

Accessing attributes of Python object in an object in a list


I am very new to Python and OOP so if there is any additional info I missed or errors in my code/logic I am hopeful for helpful criticism.

I have an object in the location class initialized as such:

class Location:
   def __init__(self,x,y):
        self.x = x
        self.y = y

location1 = Location(0,0)
location2 = Location(1,1)

This object is then passed as an attribute into a class called Passenger and a class called Car, which are both initialized as such:

class Passenger:
    def __init__(self, passenger_name, location):
        self.passenger_name = passenger_name
        self.location = location

passenger1 = Passenger("John Doe", location1)

class Car:
    def __init__(self, car_name, location, cost_per_mile):
        self.car_name = car_name
        self.location = location
        self.cost_per_mile = cost_per_mile

car1 = Car("car1", location2, 0.5)

Then finally, I have a class initialized into the variable "mobileApp"

class CarSharingApp:
    cars = []
    passengers = []

    def __init__(self):
        pass

    def add_car(self,car):
        CarSharingApp.cars.append(car)
        print(f"Car successfully added.")

    def add_passenger(self, passenger):
        CarSharingApp.passengers.append(passenger)
        print(f"Passenger successfully added.")

mobileApp = CarSharingApp()
mobileApp.add_car(car1)
mobileApp.add_passenger(passenger1)

that holds a list of these passenger and car objects (which still both hold the Location objects inside them) as CLASS attributes rather than an instance attribute in a list naturally named "passengers" and "cars". My QUESTION is how can I now access the (x,y) coordinates of these car and passenger objects in order to use them in an equation? I need to essentially find the distance between cars and passengers.I know how to access the list itself, but not the location objects x and y attributes nested in the list of objects.


Solution

  • Note that you are modifying the CarSharingApp.cars and not self.cars, so the cars will be appended to CarSharingApp.cars instead of mobileApp.cars

    CarSharingApp.cars is a list containing car objects. CarSharingApp.cars[0] accesses the first car, CarSharingApp.cars[0].location accesses the location object of the first car And CarSharingApp.cars[0].location.x accesses its x coordinate

    x_coordinate_of_first_car  = CarSharingApp.cars[0].location.x
    y_coordinate_of_first_car = CarSharingApp.cars[0].location.y
    # similarly
    x_coordinate_of_first_passenger = CarSharingApp.passengers[0].location.x
    y_coordinate_of_first_passenger = CarSharingApp.passengers[0].location.y