0

'airplanes.ini' などの Windows の 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()関数を使用して、構成ファイルの [セクション] ごとに「飛行機」タイプの新しいオブジェクトを作成します。各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)

「これが魔法が起こる場所です」とコメントされた行はset()、属性の「セッター」を介してConfigParserのメソッドへの呼び出しを設定し、構成オブジェクトを更新する場所を示しています。setattr(plane, name, value)属性を作成する「通常の」方法だと思いますが、それは呼び出されませんconfig.set()

各セクションの項目が異なっていたり、各セクションの項目数が異なっていたりしても、構成ファイルの各セクションの項目としてオブジェクトの属性を動的に定義できる柔軟性が必要です。

これを実装する方法について何か提案はありますか? property() または setattr() が私が望むことをするとは思いません。

4

1 に答える 1

1

型を動的に作成すると、複雑になりすぎたと私は主張します。代わりに、タイプの planeをカプセル化するクラスを作成し、ファイルからの情報で満たされたインスタンスを作成します。

次に、実際の平面の別のクラスを作成します。これには、そのタイプを指す type 属性が含まれます。

于 2012-12-20T00:55:20.600 に答える