How to access a List of Objects from outside a class in python
Question: Hope you can help me on this one. I have created a list of objects because the
program that I use creates lots of agents and it is easier to keep track.I
want to access that information from outside the class, so I need to call that
list and call in the agent number(which is created from the simulator). I have
put a simplified version so you can understand better.

This is the Main Class

    
    
    from StoreCar import *
    carObject  = []
    class Machine:
       def calculation():
            VehicleID = 2 # this is genarated Austomatically from system 
    #and increases every time a vehicle enters 
            Fuel = 15 # this is also calculated automatically from system.
            carObject.append(StoreCar(VehicleID,'car')
            carObject[VehicleID-1].setFC(Fuel)
    

This is the Class StoreCar which stores all the info

    
    
    class StoreCar:
       def __init__(self, id_,name):
           self.id_ = id_
           self.name= name
           self.FCList= []
    
       def setFC(self,Fuel):
           self.FCList.append(Fuel)
    

This is the outside class that I want to access data from

    
    
     from Machine import *    
     class outsideclass:
        def getVehiData():
                # I want to access the data which was saved in Machine class from here.
    


Answer: You're not actually storing anything inside the `Machine` class. The only
thing that you _are doing_ is storing values in the (confusingly named)
`carObject`:

    
    
    from StoreCar import *
    carObject  = []
    class Machine:
       def calculation():
            VehicleID = 2 # this is genarated Austomatically from system 
    #and increases every time a vehicle enters 
            Fuel = 15 # this is also calculated automatically from system.
            # You're putting things in the `carObject` *list*, which
            # should probably just be called `cars`
            carObject.append(StoreCar(VehicleID,'car')
            self.carObject[VehicleID-1].setFC(Fuel)
    

Your code, in general, has a few problems that is probably making your life
more difficult that it needs to be right now, and will certainly make things
worse down the road. I'm _assuming_ that you're in some kind of class and this
is homework given with some specific constraints because otherwise there is
absolutely no reason to do a lot of the things that you're doing.

Here are the things I'm changing:

  * `from <module> import *` is _very_ rarely what you want to do. Just `import module`. Or, `import super_long_annoying_to_type_module as slattm` and use dot access.
  * You don't _need_ a `Machine` class, unless that's one of the parameters of your assignment. It's not doing anything except cluttering up your code. `calculation` doesn't even take `self`, so either it should be decorated with `@classmethod`, or just be a function.
  * Python naming conventions - modules (files), variables, and functions/methods should be `snake_cased`, classes should be `StudlyCased`. This won't kill you, but it's a convention that you'll see in most other Python code, and if you follow it will make your code easier to read by other Python programmers.

**cars.py**

    
    
    class StoreCar:
       def __init__(self, id_,name):
           self.id_ = id_
           self.name= name
           self.fc_list= []
    
       # If you're *setting* the fuel capacity, it shouldn't be a list.
       # (assuming that's what FC stands for)
       def add_fuel(self, fuel):
           self.fc_list.append(fuel)
    

**factory.py**

    
    
    import cars
    
    class Machine:
       def __init__(self):
           self.cars = []
           # Assuming that the vehicle ID shouldn't 
           # be public knowledge. It can still be got
           # from outside the class, but it's more difficult now
           self.__vehicle_id = 0
    
       def calculation(self):
            self.__vehicle_id += 1
            fuel = 15 # this is also calculated automatically from system.
            car = cars.StoreCar(self.__vehicle_id, 'car')
            # Typically, I'd actually have `fuel` as a parameter
            # for the constructor, i.e.
            #    cars.StoreCar(self.__vehicle_id, 'car', fuel)
            car.add_fuel(fuel)
            self.cars.append(car)
    

**somethingelse.py**

    
    
     import factory
    
     class SomeOtherClass:
        def get_vehicle_data(self):
            machine = factory.Machine()
            machine.calculate()
            print(machine.cars)
    

Note, that if I were unconstrained by any kind of assignment, I would probably
just do something like this:

    
    
    from collections import namedtuple
    
    Car = namedtuple('Car', ('id', 'fuel_capacity', 'name'))
    
    
    def gen_vehicle_ids():
        id = 0
        while True:
            id += 1
            yield id
    
    vehicle_id = gen_vehicle_ids()
    
    
    def build_car():
        return Car(id=next(vehicle_id), name='car', fuel_capacity=15)
        # If you don't want a namedtuple, you *could* just
        # use a dict instead
        return {'id': next(vehicle_id), 'type': 'car', 'fuel_capacity': 15}
    
    cars = []
    for _ in range(20): # build 20 cars
        cars.append(build_car())
    
    # an alternative approach, use a list comprehension
    cars = [build_car() for _ in range(20)]
    
    print(cars)   # or do whatever you want with them.
    

For a comparison between what you can do with the namedtuple approach vs. dict
approach:

    
    
    # dict approach
    for car in cars:
        print('Car(id={}, name={}, fuel_capacity={})'.format(
              car['id'], car['name'], car['fuel_capacity']))
    
    # namedtuple approach
    for car in cars:
        print('Car(id={}, name={}, fuel_capacity{})'.format(
              car.id, car.name, car.fuel_capacity))
    

Check out <http://pyformat.info> for more string formatting tricks.

