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

2024-03-29 10:55:11 发布

您现在位置: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)

这是存储所有信息的类存储车

^{pr2}$

这是我要从中访问数据的外部类

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

Tags: fromimport信息代理列表isdefmachine
1条回答
网友
1楼 · 发布于 2024-03-29 10:55:11

实际上,您并没有在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并使用点访问。在
  • 您不需要一个Machine类,除非这是赋值的参数之一。它除了把你的代码搞得乱七八糟之外什么都没做。calculation甚至没有使用self,所以要么用@classmethod来修饰它,要么只是一个函数。在
  • Python命名约定-模块(文件)、变量和函数/方法应该是snake_cased,类应该是StudlyCased。这不会杀死您,但这是您在大多数其他Python代码中都会看到的约定,如果您遵循它,则其他Python程序员将更容易阅读您的代码。在

汽车.py

^{pr2}$

工厂.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获取更多字符串格式设置技巧。

相关问题 更多 >