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()
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.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With