Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python variable name resolve mechanism?

How python resolves variable name?In the example at below . Why not print(Base) inside ChildA not refer to Base class? Is the Base in ChildA(Base) is referred to Bass class or string class or 'String'?

class Base(object):
    def __init__(self):
        print( "Base created")

class ChildA(Base):
    def __init__(self):
        print(Base)
        Base.__init__(self)


Base = 'string'
ChildA()
like image 975
WeiChing 林煒清 Avatar asked Feb 14 '23 04:02

WeiChing 林煒清


2 Answers

The lookup occurs dynamically at the time the code is executed. When Python gets to the line print(Base), it looks for a local variable named Base, and then looks up and up in enclosing scopes for a name Base. In this case, it finds one in the global namespace, and, at the time you call ChildA(), that variable is a string.

In other words, free (that is, non-local) variables in a function really are free: what they refer to is not "locked" at the time the function is defined, but is looked up anew each time the function is called.

Note that the Base in class ChildA(Base) does unambiguously refer to the Base class in your example. That's because the class definition is only executed once, and at that time, the name Base is pointing to that class.

like image 53
BrenBarn Avatar answered Feb 20 '23 11:02

BrenBarn


In the following sentence,

Base = 'string'

the code overwrite Base with a string object.

>>> class Base(object):
...     def __init__(self):
...         print( "Base created")
...
>>> class ChildA(Base):
...     def __init__(self):
...         print(Base)
...         Base.__init__(self)
...
>>> Base
<class '__main__.Base'>
>>> Base = 'string' # <-------
>>> Base
'string'
like image 24
falsetru Avatar answered Feb 20 '23 10:02

falsetru