Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a python property with the same name as the class member name

Tags:

python

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

like image 740
Xolve Avatar asked Feb 27 '09 13:02

Xolve


1 Answers

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.

like image 145
bobince Avatar answered Oct 21 '22 17:10

bobince