[Python]ネストされたクラスの定義と使用

Python言語では、クラスでクラスを簡単に定義し、クラスでクラスを複数回インスタンス化できます。
使用方法は次のとおりです。World
クラスでクラスAgentを定義し
、__ init__を使用しようとしましたWorldのメソッドはAgentクラスを10回インスタンス化します。

class World(object):
    def __init__(self):
        self.agent_lst = [self.Agent() for i in range(10)]

        for index,value in enumerate(self.agent_lst):
            print("the id of No.",index,"class is",id(value))

    class Agent(object):
        def __init__(self):
            print("Agent has been initialized")

if __name__ == '__main__':		# main func

    world = World()

    print("finished")

手順の結果は次のとおりです。

Agent has been initialized
Agent has been initialized
Agent has been initialized
Agent has been initialized
Agent has been initialized
Agent has been initialized
Agent has been initialized
Agent has been initialized
Agent has been initialized
Agent has been initialized
the id of No. 0 class is 2343514440656
the id of No. 1 class is 2343514440128
the id of No. 2 class is 2343514441136
the id of No. 3 class is 2343514440848
the id of No. 4 class is 2343546802432
the id of No. 5 class is 2343551371872
the id of No. 6 class is 2343551258736
the id of No. 7 class is 2343551258688
the id of No. 8 class is 2343551258784
the id of No. 9 class is 2343551258832
finished

出力結果から、Agentクラスは実際に10回インスタンス化され
、これらの10回は異なるクラス変数に対応します。
同時に、IDから、これらのクラス変数が異なるメモリアドレスを占有
していることがわかります。同じではありませんクラス変数は継続的に10回再インスタンス化されます。

おすすめ

転載: blog.csdn.net/ao1886/article/details/109596938