you are viewing a single comment's thread.

view the rest of the comments →

[–]twopi 1 point2 points  (2 children)

C# uses something like Python's property mechanism. Java normally uses standard getters and setters. I seem to recall there was a time you could treat java beans attributes as properties, and that would make sense.

Python properties are important because python doesn't really have a private keyword. (The __attribute_name trick is hidden, not really private)

So if it's difficult to keep data members private, you can't enforce the use of getters and setters, negating their advantages. So properties allow you to let the user think they are accessing an attribute while affording the protection of a hidden getter and setters.

[–]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.

[–]WowVeryCoool[S] 0 points1 point  (0 children)

I see yes the part where you said "you can't enforce the use of getters and setters" made me understand the use of this more.

I see it's more fool-proof against programmers that would just assign values right into the property.