Thanks again for your input, Thomas. I normally prefer
not_here = property(lambda self: self.__get_not_here(), lambda self, v: self.__set_not_here(v)) than not_here = property(__get_not_here, __set_not_here) Because it allows me to have a pair getter/setter (when there is a need for it). Use of lambda there is ensure derived class of A can provide their custom version of getter/setter. But decorator! Of course! Thanks for reminding me this. In your example, where does '@not_here' come from? (Sorry, this syntax is new to me) Cheers On Tue, Jul 12, 2011 at 2:23 AM, Thomas Jollans <t...@jollybox.de> wrote: > On 07/11/2011 05:54 PM, Anthony Kong wrote: > > Hi, all, > > > > This question is in the same context of my two earlier questions. This > > question was raised by some python beginners, and I would like to check > > with the list to ensure I provide a correct answer. > > > > Here is a code snippet I used to demonstrate the keyword *property*: > > > > > > class A(object): > > > > def __init__(self): > > self.__not_here = 1 > > > > def __get_not_here(self): > > return self.__not_here > > > > def __set_not_here(self, v): > > print "I am called" > > self.__not_here = v > > > > not_here = property(lambda self: self.__get_not_here(), lambda self, > > v: self.__set_not_here(v)) > > # not_here = property(lambda self: self.__not_here, lambda self, v: > > self.__not_here = v) > > > > So the question: is it possible to use lambda expression at all for the > > setter? (As in the last, commented-out line) > > > > Python interpreter will throw an exception right there if I use the last > > line ('SyntaxError: lambda cannot contain assignment'). I'd use pass a > > setter method anyway. > > > > What is your preferred solution? > > No, a lambda can only contain an expression, not a statement. This is > not C, assignments are not expressions. > > As to what I would do: > There's really no need to use lambdas at all here: > > class A(object): > def __init__(self): > self.not_here = 1 > def __get_not_here(self): > return self.__not_here > def __set_not_here(self, val): > self.__not_here = val > not_here = property(__get_not_here, __set_not_here) > > My favourite way to create properties is of course with decorators: > > class A(object): > def __init__(self): > self.not_here = 1 > > @property > def not_here(self): > return self.__not_here > > @not_here.setter > def not_here(self, val): > self.__not_here = val > -- > http://mail.python.org/mailman/listinfo/python-list > -- Tony Kong *blog:* www.ahwkong.com Don’t EVER make the mistake that you can design something better than what > you get from ruthless massively parallel trial-and-error with a feedback > cycle. That’s giving your intelligence *much* too much credit. - Linus Torvalds
-- http://mail.python.org/mailman/listinfo/python-list