2016-06-08 54 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