3

サーバーに接続されているコンピューターのリストを生成しています。各コンピューターについて、プロパティのリストを収集します。私はPythonとプログラミングが初めてで、私のソリューションはかなり不格好です。

私はリストでこれを行っていました。マスター リストがcomputer_listあります。各コンピューターは、ステータス、日付、プロファイルなどの属性を持つ別のリストです。

computer_list = [cname1, cname2, cname3]
cname1 = ['online', '1/1/2012', 'desktop']

この方法の欠点は、私がこのプログラムに取り組み、変更すればするほど明らかになります。もっと直感的なものを期待しています。私は辞書を調べましたが、その解決策は私のものと同じくらい複雑に思えます。リスト内のリストは実行可能ですが、反復と割り当てを開始すると読み取れません。もっと良い方法があると確信しています。

4

2 に答える 2

4

Computerコンピュータのプロパティと状態を説明するフィールドを格納するオブジェクトを作成することは、実行可能なアプローチです。

クラスについてもっと読む必要がありますが、以下のようなものがあなたのニーズに合うはずです:

class Computer(object):
    def __init__(self, status, date, name):
        self.status = status
        self.date = date
        self.hostname = name

    # (useful methods go here)

おそらく、Computerオブジェクトを初期化して、次のようにリストに保存します。

comp1 = Computer("online", "1/1/2012", "desktop")
comp2 = Computer("offline", "10/13/2012", "laptop")

computers = [comp1, comp2]
于 2013-01-22T18:26:56.043 に答える
2

各コンピューターをオブジェクトにします。

class Computer(object):
    def __init__(self, name, status, date, kind):
        self.name   = name
        self.status = status
        self.date   = date
        self.kind   = kind

    @classmethod    # convenience method for not repeating the name
    def new_to_dict(cls, name, status, date, kind, dictionary):
        dictionary[name] = cls(name, status, date, kind)

次に、これらを辞書またはリストに保存します。

computer_list = []
computer_list.append(Computer("rainier", "online", "1/1/2012", "desktop"))

computer_dict = {}
Computer.new_to_dict("baker", "online", "1/1/2012", "laptop", computer_dict)

それらを反復処理すると、次のようになります。

for comp in computer_list:
    print comp.name, comp.status, comp.date, comp.kind

__str__()クラスで定義して、それらの表示方法などを定義することもできます。

于 2013-01-22T18:29:55.453 に答える