【Python】嵌套类的定义与使用

在 python 语言中我们能够方便地在类中定义类,在类中多次实例化类;
使用方法如下;
我们试图在 World 这个 class 里定义了一个 class Agent;
并试图在 World 的__init__方法中对 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