Introduction to the import mechanism of python global variables, pythonimport

Source: Internet
Author: User

Introduction to the import mechanism of python global variables, pythonimport

First, let's share the problematic code:

IServer. py

from abc import ABCMeta, abstractmethodprint __name__class IServer:  def __init__(self):    pass  @abstractmethod  def DoWithA(self):    pass  @abstractmethod  def DoWithB(self):    pass

IServer_A.py

import IServerserverType ='1001'print __name__dir()from CreatFactory import GLOBAL_class_dicdir()class IServer_A(IServer.IServer):  def __init__(self):    pass  def DoWithA(self):    print 'Server_A do with interface A'  def DoWithB(self):    print 'Server_A do with interface B'global GLOBAL_class_dicprint 'the id of GLOBAL_class_dic in A is:',id(GLOBAL_class_dic)GLOBAL_class_dic[serverType] = IServer_Aprint 'GLOBAL_class_dic in a is:', GLOBAL_class_dic

IServer_ B .py

import IServerserverType ='1002'from CreatFactory import GLOBAL_class_dicprint __name__class IServer_B(IServer.IServer):  def __init__(self):    pass  def DoWithA(self):    print 'Server_B do with interface A'  def DoWithB(self):    print 'Server_B do with interface B'print 'the id of GLOBAL_class_dic in B is:',id(GLOBAL_class_dic)GLOBAL_class_dic[serverType] = IServer_Bprint 'GLOBAL_class_dic in b is:', GLOBAL_class_dic

CreatFactory. py

# Coding: UTF-8import OS; import sys; import threadingfrom misc import * global GLOBAL_class_dicGLOBAL_class_dic = {1:1} print 'Global _ class_dic in define is :', GLOBAL_class_dicprint 'the id of GLOBAL_class_dic in define is: ', id (GLOBAL_class_dic) dir () import into IServer_Bdef CreateServer (serverType): global GLOBAL_class_dic print 'Global _ class_dic in use is :', GLOBAL_class_dic print 'the id of GLOBAL_class_dic in USE is: ', id (GLOBAL_class_dic) if GLOBAL_class_dic.has_key (serverType): return GLOBAL_class_dic [serverType] else: return 'no' if _ name _ = '_ main _': pass # After receiving the message, obtain serverType from the db Based on the message content, assume that the obtained serverType = 1001 print 'main' print 'Global _ class_dic in main A is: ', GLOBAL_class_dic serverType = '000000' server = CreateServer (serverType) print 'Global _ class_dic in main B is: ', GLOBAL_class_dic print 'server:', server. doWithA (server ())

Run CreatFactory. py with debugging information added to the Code. DoWithA fails to be called, and AttributeError: 'str' object has no attribute 'dowitha' is displayed '. The running result is as follows:

D:\Python27\python.exe "D:/DesignMode/Server --00/CreatFactory.py"GLOBAL_class_dic in define is: {1: 1}the id of GLOBAL_class_dic in define is: 36230176['GLOBAL_class_dic', 'Misc', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'binascii', 'inspect', 'minidom', 'os', 'struct', 'sys', 'threading']IServerIServer_A['IServer', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'serverType']GLOBAL_class_dic in define is: {1: 1}the id of GLOBAL_class_dic in define is: 36230032['GLOBAL_class_dic', 'Misc', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'binascii', 'inspect', 'minidom', 'os', 'struct', 'sys', 'threading']['IServer', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'serverType']['GLOBAL_class_dic', 'IServer', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'serverType']IServer_Bthe id of GLOBAL_class_dic in B is: 36230032GLOBAL_class_dic in b is: {1: 1, '1002': <class IServer_B.IServer_B at 0x022C2ED8>}['GLOBAL_class_dic', 'IServer', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'serverType']the id of GLOBAL_class_dic in A is: 36230032GLOBAL_class_dic in a is: {1: 1, '1002': <class IServer_B.IServer_B at 0x022C2ED8>, '1001': <class IServer_A.IServer_A at 0x02273420>}mainGLOBAL_class_dic in main A is: {1: 1}GLOBAL_class_dic in use is: {1: 1}the id of GLOBAL_class_dic in USE is: 36230176GLOBAL_class_dic in main B is: {1: 1}server : noTraceback (most recent call last): File "D:/DesignMode/Server --00/CreatFactory.py", line 38, in <module>  server.DoWithA(server())AttributeError: 'str' object has no attribute 'DoWithA'Process finished with exit code 1

From the running result, we can see that GLOBAL_class_dic is defined twice. There are two different IDs. One memory is allocated for the first definition, and another memory is re-allocated for the second unknown reason. Then all the automatic registration of the service is registered in the memory, when the main function is used, the memory requested for the first time is used, which causes program running to fail. That's the question. Why is it allocated again?

The reason why the global variable is redefined is because CreatFactory is being executed. in py, GLOBAL variables are defined at the beginning. In this case, the functions and variables that can be used in the namespace are printed: ['Global _ class_dic ', 'misc',' _ builtins __', '_ doc _', '_ file _', '_ name _', '_ package _', 'binascii ', 'inspect ', 'minidom ',' OS ', 'struct', 'sys ', 'threading', and after importing IServer_A, in IServer_A.py, when the available functions and variables are printed from CreatFactory import GLOBAL_class_dic, ['iserver ',' _ builtins _ ',' _ doc __', '_ file _', '_ name __' , '_ Package _', 'servertype'], there will be no GLOBAL_class_dic. If the program finds no, it will be declared again. It seems that the cause of the problem has been found.

Python has two import scenarios: one is the normal import statement before the file, and the other is the special scenario: __main _ is an import system relative to Python. Run CreatFactory. when the py file is run, the printed value of __name _ is _ main __. when the subclass is imported again, the system searches for whether _ name __= CreatFactory has been imported in the current namespace, we found that this module does not exist, so we imported it again. The global variable is redefined and allocated memory. Later, the global variable will be used in the subclass service, in the main function, global variables defined for the first time in the current scope are used.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.