简体   繁体   中英

Access properties of object that is an array in another object in Python

I have two classes: CarRentComp and Cars.

CarRentComp has an array of cars. I need to insert to DB the CarRentComp and one Car (so the array is length 1 for now).

My problem is that I can't actually access the Cars properties.

I come from a Java/C# background so I'm trying to translate some of what I did to Python.

The two files:

class Car():
__plate=""

def set_plate(self, pPlate):
    self.__plate=pPlate

def get_plate(self):
    return self.__plate

def __init__(self,pPlate):
    self.set_plate(pPlate)

from car import Car
class CarRentComp():
__name=""
__cars=[Car("")]

def set_name(self, pName):
    self.__name=pName
def get_name(self):
    return self.__name

def set_cars(self, pCars):
    self.__name=pCars

def get_cars(self):
    return self.__cars

def __init__(self,pName, pCars):
    self.set_name(pName)
    self.set_cars(pCars)

from carrentcomp import CarRentComp
class OpsCarRentComp():

    def insert_carrentcomp(self, carrentcomp = CarRentComp):
        name = carrentcomp.get_name()
        vehicles = carrentcomp.get_cars()

        car1 = vehicles[0]

        plate = car1..get_plate()

I'm calling insert_carrentcomp from another file and adding the CarRentComp and its car to the array:

car1 = Car("AAA2345")

add_car_rent_comp= CarRentComp("Deluxe Cars", [car1])

OpsCarRentComp.insert_carrentcomp(OpsCarRentComp, add_car_rent_comp)

I can't access the cars properties, like its plate from the class OpsCarRentComp.

plate = car1..get_plate() --when I compare it to CarRentComp, it is one of the arguments that my method takes. I'm kind of struggling with Python and its simpler way to do things.

As the insert_carrentcomp method is not using self, you might want to make it @staticmethod .

Try something like:

class OpsCarRentComp:
    @staticmethod
    def insert_carrentcomp(carrentcomp: CarRentComp):
        name = carrentcomp.get_name()
        vehicles = carrentcomp.get_cars()

        car1 = vehicles[0]

        plate = car1.get_plate()

car1 = Car("AAA2345")

add_car_rent_comp= CarRentComp("Deluxe Cars", [car1])

OpsCarRentComp.insert_carrentcomp(add_car_rent_comp)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM