Reason for globals() in Python?

前端 未结 8 868
北荒
北荒 2020-12-12 12:43

What is the reason of having globals() function in Python? It only returns dictionary of global variables, which are already global, so they can be used anywhere... I\'m ask

8条回答
  •  再見小時候
    2020-12-12 13:03

    It can also be used to get an instance of the class 'classname' from a string:

    class C:
        def __init__(self, x):
            self.x = x
            print('Added new instance, x:', self.x)
    
    
    def call(str):
        obj = globals()[str](4)
        return obj
    
    c = call('C')
    print(c.x)
    

提交回复
热议问题