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

259 views Asked by At

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?

1

There are 1 answers

1
Jonathon Reinhart On BEST ANSWER

You need to use self. when accessing member variables:

def __init__(self):
    self.__pro = 1

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