python - Confused about variable scope using matplotlib -- axis object -


I do not know why the following code works: If I comment on ax assignments in main, then to do this work How does the ax get in the purview of the ceremony? This version of Python is 2.7.2.

After a little more research, I have found that all variables are seen in the main block defined function in this same code module. I did not know that the dragon worked like this! Each variable in the Main block is visible to all functions in the same source file. It does not kill me desirable! How it works is that I think this exception has been made for the Main code block, but I will not be guessed.

): Ax.plot ([1], [ 2]) # How is this ever defined? Return if (__name__ == "__main__"): fig = plt.figure () plt.clf () ax = plt.subplot (111, polar = true) # If I comment it out, then the ax function defined the error Call plt.hold (true) f ()

"This is the form of me It's desirable to do that! It seems to be about which work. "

You should avoid having global variables in your code. Note that the main block you are talking about is a global name space (that module / script) is a statement, but that does not mean that the "main" block is suddenly a special task.

What you can do (which is considered to be better anyway):

  PLT Def F () as imported pylab: ax.plot ([1 ], [2]) # It is no longer defined defrade (main): fig = plt.figure () plt.clf () ax = plt.subplot (111, polar = true) # ax main () function only local Is Plt.hold (True) f () if __name__ == "__main__": # no-bracket for if-statement; Very unpathic main ()   

Now, this will be the reason of an error every time, because ax can be found only in main () , And the global (module) namespace is not in place.

Comments

Popular posts from this blog

java - ImportError: No module named py4j.java_gateway -

python - Receiving "KeyError" after decoding json result from url -

.net - Creating a new Queue Manager and Queue in Websphere MQ (using C#) -