简体   繁体   中英

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 ?

You need to use self. when accessing member variables:

def __init__(self):
    self.__pro = 1

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM