Search code examples
pythonpython-2.7ooppropertiesencapsulation

Python 2.7 @property usage results in error "global name '_c__pro' is not defined"


I wrote a simple class in Python2.7 that should use the @property functionality.

class c():
    def __init__(self):
        __pro = 1

    @property
    def pro(self):
        return __pro *10

    def setpro(self, x):
        __pro = x

Now when I create an object from this class and try to access the pro property, I get the following error:

>>> x = c()
>>> x.pro
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 7, in pro
NameError: global name '_c__pro' is not defined

Note that the whole thing was written inside the same python commandline-session, so it should have nothing to do with missing imports or wrong import namespaces.

What am I doing wrong here? How must I rewrite it to access the property pro?


Solution

  • You need to use self. when accessing member variables:

    def __init__(self):
        self.__pro = 1
    
    @property
    def pro(self):
        return self.__pro *10