QtotheC QtotheC - 5 months ago 6x
Python Question

Accessing "private" variable behind python property

How do you access the "private" variable behind a Python property?

In the following code, I get

Hello World
instead of the
World World
that I expect. I would guess that the property has a different scope that results in
being different in the property than the module. If so, is there a way to access the underlying variable? Or is there a different idiom to use for "code outside the class should use a different getter than code in the class"?

class Foo():
def __init__(self):
self._x = 'Hello'
self.x = 'World'

def x(self):
return self._x

def x(self, val):
self._x = val

foo = Foo()

101 101

You are accessing the private variable _x via foo._x.

What is typical in this situation is to not define the x attribute at all, i.e. remove the line self.x = 'World'. That way you are using the property x to access the attribute _x (and because privates aren't really private you can of course also access the attribute directly using _x).

Edit: the first part of my answer was wrong, see user2357112's answer for why you are not getting the expected output.