how does scope work when using property in Python 3?

Question:

Newbie question about scope: in the following example, how is property able to get access to getx and setx etc. That is, why don’t those names have to be qualified with a C.getx, for example? The code is directly from the python docs (https://docs.python.org/3/library/functions.html#property):

class C:
    def __init__(self):
        self._x = None

    def getx(self):
        return self._x

    def setx(self, value):
        self._x = value

    def delx(self):
        del self._x

    x = property(getx, setx, delx, "I'm the 'x' property.")

Update: based on comment

Conversely if I had a class like this

class A:
    def foo(self):
        print("foo")

    def bar(self):
        foo(self)

This would fail. Is that because CPython has no idea what’s in bar until I actually try to run it (and at that point we are no longer in the class scope)?

Asked By: Alex

||

Answers:

The class is its own namespace until it is finalized, and so names inside it don’t need to be qualified during class definition. (In fact, they can’t be: the class doesn’t yet have a name, so there is no way to specify the class as a namespace.)

class C:
    a = 0
    b = a + 1   # uses a from preceding line

In your class definition, getx, setx, and delx can be used unqualified because the property(...) call is executed during class definition.

After the class is finalized, the class has a name, and for methods that are called on instances, the instance has a name (traditionally self). Accessing attributes and methods at this point requires qualifying the name with either the class or instance reference (e.g. C.foo or self.foo).

Answered By: kindall

That is because there are two different scopes. One is Class and one is function.

When you define a function in a class, that function is defined in Class scope. You can build a minimal example:

class A:
    a = 1
    b = a + 1
    pass

You can see that when defining b, we can directly access variable a as they are in the same scope A Class.

But when you use a Class scope variable in a function, that is another scope function. So in this case you need to manually specify scope.

Actually, this behave varies from language to language.

Answered By: Sraw
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.