0

I am trying to write Python properties with using less code, I'd like to define getter and setter functions with lambdas.

So, I try like this:

class Text(object):

    content = property(lambda self: self._content,
                       lambda self,content: self._content = content)

    def __init__(self, content):
        self._content = content
        pass

But unfortunately, I get error on second lambda expression (on setter), because you can't define lambda with assignment, right?

So is there some other way to writing a property (preferably inline) that would take less code. Private attribute _content is of type string, is there a way to assign a value to string without = operator.

Scarass
  • 914
  • 1
  • 12
  • 32
  • Why are you even defining a property in the first place if [you're not doing anything with the value](https://archive.org/details/SeanKellyRecoveryfromAddiction)? – Ignacio Vazquez-Abrams Apr 22 '17 at 15:00
  • Look at this http://stackoverflow.com/questions/6282042/assignment-inside-lambda-expression-in-python – julian salas Apr 22 '17 at 15:03
  • Haha, I just prefer concept of encapsulation from OOP :P. Maybe it's not that important in this example, but it might make more sense for some larger classes. How come you know I don't need this for some larger class, and this is just an example? :P – Scarass Apr 22 '17 at 15:03
  • Because if this was a larger class you wouldn't care about saving two lines of code. – Ignacio Vazquez-Abrams Apr 22 '17 at 15:04
  • Of course I would, it actually takes 4 lines to write getter and setter, plus an empty line between them. – Scarass Apr 22 '17 at 15:14

1 Answers1

1

You can do that like this:

content = property(lambda self: self._content,
                   lambda self,content: setattr(self, '_content' ,content))
RaminNietzsche
  • 2,683
  • 1
  • 20
  • 34