2016-06-08 59 views
-1

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

这是主类

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. 
访问数据的课外
+0

我想要的是从外部类访问存储在机器类(车辆数据)中的数据。如果我不清楚请让我知道。谢谢@LogicStuff – DrakonianD

+0

很难为你提供帮助,因为看起来你需要了解更多关于面向对象的知识,并重新思考你的程序的整个方案。此外,您应该[创建一个简化的示例](https://stackoverflow.com/help/mcve)(但包含您的主脚本),并避免谈论与您的问题无关的事情(例如,看起来我们不喜欢不需要了解代理号码或模拟器等背景信息......)。 – zezollo

回答

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) 

您的代码,在一般情况下,有可能是让你的生活更加困难,它需要有一个几个问题现在,并且肯定会让事情变得更糟。我是假设,你在某种类别,这是给予一些具体的约束作业,否则绝对没有理由做很多事情,你在做什么。

这里是我改变的东西:

  • from <module> import *非常很少,你想要做什么。只需import module。或者,import super_long_annoying_to_type_module as slattm并使用点访问。
  • 您不需要需要 a 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 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更多的字符串格式化TR icks。

+0

难道你不能用'itertools.count()'替换'gen_vehicle_ids():'吗? –

+0

@TerrenceBrannon是的。尽管如此,OP提到这些ID是由生成的,所以如果它们不是连续的,那么生成器会更好地工作。但是你是对的,如果他们只是连续的,那么'itertools.count()'会是更好的选择。 –

+0

@WayneWerner感谢您解释清楚的答案。我使用Machine类的原因是为了避免混淆,但它似乎使问题更加混乱。我正在使用车辆轨迹模拟器,因此模拟器中的API将用作机器类。因为它是一个模拟器,它会生成车号和燃油消耗值。我想要做的是用汽车ID节省燃油消耗值。所以当我想要的时候,我可以调用VehicleID并从外部类中获取燃料消耗值。 – DrakonianD