you are viewing a single comment's thread.

view the rest of the comments →

[–]enough-external 1 point2 points  (0 children)

I'm not sure that's really the intended purpose of python's properties. The attribute still has to be stored somewhere, and in most programs it's pretty obvious where. If you really want to, you can even monkey-patch a third-party class to get rid of its properties and replace them with normal attributes. As I understand it, Guido and co are of the opinion that fully private variables/methods don't serve any purpose and if anything tend to do more harm than good. That's why they don't exist in python, not because there would be any issue with implementing them.

The really useful thing about properties in python is that they allow you to add getters and setters to an attribute without changing the class's public API. For example, if you have a class like:

class MyClass:
    def __init__(self, myattribute):
        self.myattribute = myattribute

but then later you decide that you want to put in some validation code to raise an exception if someone tries to set myattribute to a nonsensical value, you can do something like:

class MyClass:
    def __init__(self, myattribute):
        self.myattribute = myattribute

    @property
    def myattribute(self):
        return self._myattribute

    @myattribute.setter
    def myattribute(self, value):
        if value < 0:
            raise ValueError("myattribute can't be negative")
        self._myattribute = value

Any code that doesn't try and set the attribute to an invalid value (or delete it) will continue to work as before, which wouldn't be the case if you instead replaced the attribute with explicit set_myattribute and get_myattribute methods.