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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With