TransWikia.com

How to check local and global scope in Python and override variables in a class?

Stack Overflow Asked by suresh on December 18, 2020

I am learning Python scope and unable to understand with a program, here is my code

a = "bat"
class Test():
    a = "ball"    
    b = [a for i in range(2)]
    e = lambda: a
    @staticmethod
    def f():
        return a
        
    g = lambda a=a: a
    d = a

print(Test.b)  # prints ["bat","bat"]
print(Test.e()) # prints bat
print(Test.f()) # prints bat
print(Test.g()) # prints ball
print(Test.d)  # prints ball

Here I have declared variable a="bat" outside the class and then I declared variable a="ball" inside class which is local to it. When I access the local a="ball" inside the class how is it returning the variable a="bat" declared outside the class in first 3 prints & not in the last 2 prints?

One Answer

When a class is created, there is a new namespace for the class. a (the second one), b, e, f,g and d are all created in the class namespace. Any time you try to access a from within that same namespace, it gets the inner "ball" value, but for any new scope it will first try to find a in its local namespace, then skip the class namespace and use the global namespace.

For d = a, it is inside the class namespace so is "ball". For g = lambda a=a: a, when resolving the a inside the lambda the function, it finds the a in the local namespace which was set to a default value when in the class namespace, so it resolves to "ball".

For all others, they try to access a from a local namespace, but do not find it, so check the global namespace and find it there.

Answered by Oli on December 18, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP