Search code examples
pythonencapsulation

Does python support private variables?


I have heard that "“Private” instance variables that cannot be accessed except from inside an object don’t exist in Python : as seen here

However, we can create private variables using getter and setter methods in python as seen below

class C(object):
    def getx(self):
        return self._x

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

    x = property(fset=setx)

c = C()
c.x = 2
print c.x

When I try to access c.x, I am getting the error seen below:

Traceback (most recent call last):
  File "d.py", line 12, in <module>
    print c.x
AttributeError: unreadable attribute

Does the fact that c.x is not accessible mean that x behaves like a private variable? How does this fact relate to what is said in the link above?


Solution

  • There is a lot of literature on this topic, but in short:

    Python is different to programming languages that have actually "private" attributes in that no attribute can be truly inaccessible by other functions. Yes, we can simulate the behaviour of languages like Java using property, as you've shown, but that is kind of fudging "true" private attributes. What property actually is is a higher-order function (well, technically, it's a decorator), so when you call c.x, although it acts as a property, you're really referring to a function that controls whether you can use the getters and setters defined in it.

    But just because c.x doesn't allow direct read access, doesn't mean that you can't call print c._x (as @avigil pointed out). So c._x isn't really private - it's just as easily accessible as any other attribute belonging to the C class. The fact that its name starts with an underscore is just a convention - a signal to fellow programmers: "Please don't handle this variable directly, and use the getters/setters instead" (if available).