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.

5
  • Why are you even defining a property in the first place if you're not doing anything with the value? Commented Apr 22, 2017 at 15:00
  • Look at this stackoverflow.com/questions/6282042/… Commented Apr 22, 2017 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 Commented Apr 22, 2017 at 15:03
  • Because if this was a larger class you wouldn't care about saving two lines of code. Commented Apr 22, 2017 at 15:04
  • Of course I would, it actually takes 4 lines to write getter and setter, plus an empty line between them. Commented Apr 22, 2017 at 15:14

1 Answer 1

1

You can do that like this:

content = property(lambda self: self._content,
                   lambda self,content: setattr(self, '_content' ,content))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.