[Python] The definition and use of nested classes

In the python language, we can easily define the class in the class, and instantiate the class multiple times in the class; the
method of use is as follows;
we tried to define a class Agent
in the World class; and tried to use the __init__ method in World Instantiate the Agent class 10 times;

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")

The result of the procedure is;

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

From the output results, the Agent class is indeed instantiated 10 times;
and these 10 times correspond to different class variables;
at the same time, it can be seen from the id that these class variables occupy different memory addresses; it
proves that they are not the same The class variable is continuously re-instantiated 10 times;

Guess you like

Origin blog.csdn.net/ao1886/article/details/109596938