Python - 从动态创建的对象的属性调用其他对象的函数

时间:2012-12-20 00:47:23

标签: python

给出一个Windows ini风格的配置文件,例如'airplanes.ini':

[JumboJet]
wingspan = 211
length = 231
seating = 416
crew = 2
unit_cost = 234000000
on_hand = 3

[SopwithCamel]
wingspan = 28
length = 18
armament = twin Vickers
crew = 1
on_hand = 1

[NCC1701]
length = 289 meters
crew = 430
speed = Warp 8
armament = 12 phasers, 6 photon torpedo

我使用Python 2.7.3库中的ConfigParser模块读取文件内容,然后使用内置type()函数为每个[section]创建一个“Airplane”类型的新对象]在配置文件中。每个name = value对都成为对象的属性:

# create a config parser, using SafeConfigParser for variable substitution
config = ConfigParser.SafeConfigParser()

# read in the config file
config.read('airplanes.ini')

airplanes = []

# loop through each "[section]" of config file
for section in config.sections():
    # create a new object of type Airplane
    plane = type("Airplane",(object,),{"name":section})

    # loop through name = value pairs in section
    for name, value in config.items(section)
        # this is where the magic happens?
        setattr(plane, name, lambda: config.set(section,name,value))

    airplanes.append(plane)

# do stuff with Airplanes,
boeing = airplanes[1]

# this update needs to call through to config.set()
boeing.on_hand = 2

# then save the changes out to the config file on disk
with open('airplanes.ini','wb') as f:
    config.write(f)

该行评论“这是魔术发生的地方”表示我想通过属性的“setter”设置对ConfigParser的set()方法的调用,以更新配置对象。我相信setattr(plane, name, value)是创建属性的“常用”方式,但不会调用config.set()

我希望灵活地动态定义对象的属性作为配置文件每个部分中的项目,即使每个部分中的项目不同,或者每个部分具有不同数量的项目。

有关如何实施此建议的任何建议?我不认为property()或setattr()会做我想做的事。

1 个答案:

答案 0 :(得分:1)

我认为使类型动态过于复杂。相反,我会创建一个封装类型的平面的类,并创建填充了文件中信息的实例。

然后你有一个单独的实际平面类,它包含一个指向它所属类型的类型属性。