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)?
Advertisement
Answer
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
).