Combine accessors into one method

When setting the property accessor properly in Python, it is common to write as follows using the property function. For example, if you want to attach the bar property to the Foo class.

class Foo(object):
    def __get_bar(self):
        return self.__bar

    def __set_bar(self, value):
            self.__bar = value

    def __del_bar(self):
            del self.__bar

    bar = property(__get_bar, __set_bar, __del_bar,
                   doc="short explanation for bar property")

However, with this writing method, it is necessary to create as many as three methods for one property, which is confusing.

In such a case, it is also possible to write this collectively as follows. Top and bottom have the same meaning.

class Foo(object):
    def bar():
        doc = "short explanation for bar property"

        def fget(self):
            return self.__bar

        def fset(self, value):
            self.__bar = value

        def fdel(self):
            del self.__bar

        return locals()

    bar = property(**bar())

Can be omitted if you don't need fdel () or doc.

It's a little easier to see because one method with the same name is grouped for one property ... I feel.

Recommended Posts

Combine accessors into one method
[Python] Combine multiple Excel sheets into one
Combine python function arguments into one variable
Combine multiple python files into one python file
[Python & Unix] Combine multiple PDF files into one.
Combine multiple Excel files loaded using pandas into one