I have something like this:
class X():
def __init__(self):
self.__name = None
def _process_value(self, value):
# do something
pass
def get_name(self):
return self.__name
def set_name(self, value):
self.__name = self._process_value(value)
name = property(get_name, set_name)
Can I replace get_name and set_name using lambda functions?
I’ve tried this:
name = property(lambda self: self.__name, lambda self, value: self.__name = self.process_value(value))
but compiler doesn’t like my setter function.
Your problem is that lambda’s body must be an expression and assignment is a statement (a strong, deep distinction in Python). If you insist on perpetrating
lambdas you’ll meet many such cases and learn the workarounds (there’s usually one, though not always), such as, in this case:i.e. use the built-in
setattr(which is a function and thus acceptable in alambda‘s body) rather than assignment (which is a statement and thus unacceptable in alambda‘s body).You also need to perform the name-mangling for the dual-underscore attribute manually (changing
__nameto_X__nameas you’re in class X) where the attribute name is presented as a quoted string, as it must be insetattr, as the Pyhon compiler only does the name mangling in question for suitable identifiers, not for string literals.