如何在python中从类外部访问对象列表

时间:2016-06-08 12:58:54

标签: python class object dictionary access

希望你能帮我解决这个问题。 我创建了一个对象列表,因为我使用的程序创建了很多代理,并且更容易跟踪。我想从类外部访问该信息,所以我需要调用该列表并调用代理号(这是从模拟器创建的)。 我已经放了一个简化的版本,这样你就能更好地理解。

这是主类

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)

这是存储所有信息的类StoreCar

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

   def setFC(self,Fuel):
       self.FCList.append(Fuel)

这是我想从

访问数据的外部类
 from Machine import *    
 class outsideclass:
    def getVehiData():
            # I want to access the data which was saved in Machine class from here.

1 个答案:

答案 0 :(得分:1)

您实际上并未在Machine课程中存储任何内容。您正在做的唯一事情是将值存储在(容易混淆的名称)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)

一般来说,您的代码存在一些问题,这些问题可能会使您的生活变得更加艰难,现在需要做到这一点,并且肯定会让事情变得更糟。我假设你在某种类中,这是一些特定约束的家庭作业,因为否则你没有理由做很多你正在做的事情。 / p>

以下是我要改变的事情:

  • from <module> import * 非常很少你想做什么。只需import module。或者,import super_long_annoying_to_type_module as slattm并使用点访问。
  • 您不需要 Machine课程,除非这是您作业的参数之一。除了弄乱你的代码之外,它没有做任何事情。 calculation甚至不会self,因此它应该使用@classmethod进行修饰,或者只是一个函数。
  • Python命名约定 - 模块(文件),变量和函数/方法应为snake_cased,类应为StudlyCased。这不会让你失望,但是你会在大多数其他Python代码中看到这个惯例,如果你遵循它将使你的代码更容易被其他Python程序员阅读。

<强> 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)

请注意,如果我不受任何类型的任务限制,我可能会做这样的事情:

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.

比较你可以用namedtuple方法和dict方法做什么:

# 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))

查看http://pyformat.info了解更多字符串格式化技巧。