tags:

views:

203

answers:

1

Is it possible in python to create a property with the same name as the member variable name of the class. e.g.

Class X:
    ...
    self.i = 10 # marker
    ...
    property(fget = get_i, fset = set_i)

Please tell me how I can do so. Because if I do so, for the statement at marker I get stack overflow for the assingm

+13  A: 

Is it possible in python to create a property with the same name as the member variable name

No. properties, members and methods all share the same namespace.

the statement at marker I get stack overflow

Clearly. You try to set i, which calls the setter for property i, which tries to set i, which calls the setter for property i... ad stackoverflowum.

The usual pattern is to make the backend value member conventionally non-public, by prefixing it with ‘_’:

class X(object):
    def get_i(self):
        return self._i
    def set_i(self, value):
        self._i= value
    i= property(get_i, set_i)

Note you must use new-style objects (subclass ‘object’) for ‘property’ to work properly.

bobince
+1, Beat me to it :)
Kiv
-1: forget to quote the documentation: http://docs.python.org/library/functions.html#property
S.Lott