thw
thw

Reputation: 13

Setting a Python property from __init__()

I want to define a class that ensures some constraints when a property is set/modified. Furthermore, I want to be able to set the property value on construction, with the same constraints. Simplified example:

class MyClass(object):
    def __init__(self, attrval):
        self.myattr = attrval
    
    @property
    def myattr(self):
        return self._myattr

    @myattr.setter
    def myattr(self, value):
        if value is None:
            raise ValueError("Attribute value of None is not allowed!")
        self._myattr = value

I'm calling the property setter right from __init__(), so the property is the only place where self._myattr is accessed directly. Are there any problems or caveats in using a property like this (like a missing or invalid creation of _myattr)? Maybe when (multiple) inheritance comes in? Is there a PEP or some other "official" statement about how to properly initialize properties from __init__()?

Most property examples I found do not use the property setter from the constructor. In How to set a python property in __init__, the underlying attribute gets created explicitly before setting the property. Some people think that each single attribute must be explicitly initialized in __init__(), that's why my code example feels a bit odd.

Upvotes: 1

Views: 1558

Answers (1)

Moses Koledoye
Moses Koledoye

Reputation: 78554

There won't be any problems. Use what works for you.

One thing to keep in mind is that setting the attribute using the setter runs the validation you've set up. Setting the attribute directly in the __init__ won't have that validation executed. This would make the setter version more slower, but safer as per disallowing certain values.

Upvotes: 2

Related Questions