Woody1193
Woody1193

Reputation: 7980

Writing a function to define class properties

I was recently writing a definition for a pretty basic data class in Python and I came up with the following:

class A:

    def __init__(self, **kwargs):
        self.__a1 = kwargs.get('some_value', -1)

    @property
    def a1(self):
        return self.__a1

    @a1.setter
    def a1(self, new_a1):
        self.__a1 = new_a1

And it goes on. In this case, the value -1 could be replaced with a variety of "null" values: -1, "", [], etc., and some_value comes from an Enum I defined earlier.

Because the class definition contains several of these property definitions, and they're all very "same-y", I'd like to write a function to do this for me. I'm pretty sure it's possible in Python but I've never tried it so I was hoping for some pointers.

Upvotes: 1

Views: 98

Answers (1)

jonrsharpe
jonrsharpe

Reputation: 122032

Assuming you want to simplify the repetitive property definitions, you can use a generic descriptor to simplify this significantly:

class ProtectedAttribute(object):
    """Basic descriptor functionality for a protected attribute.

    Args:
      name (str): The name of the attribute to back the descriptor
        (usually the name the descriptor is assigned to with a single
        additional leading underscore).

    """

    def __init__(self, name, **kwargs):
        self.name = name

    def __get__(self, obj, typ):
        return getattr(obj, self.name)
    
    def __set__(self, obj, value):
        setattr(obj, self.name, value)
        
    def __delete__(self, obj):
        delattr(obj, self.name)

Now you can just do:

class A(object):

    a1 = ProtectedAttribute('__a1')

    def __init__(self, **kwargs):
        self.a1 = kwargs.get("some_value", -1)

Note also the use of dict.get to simplify __init__.

Upvotes: 2

Related Questions