Encapsulation unpythonic?
Ethan Furman
ethan at stoneleaf.us
Mon Sep 2 00:15:03 EDT 2013
On 09/01/2013 05:59 PM, Roy Smith wrote:
> Ethan Furman wrote:
>> On 09/01/2013 02:54 PM, Tim Delaney wrote:
>>> Roy Smith wrote:
>>>>
>>>> Nothing is accessible in Python except via getters and setters. The
>>>> only difference between Python and, say, C++ in this regard is that the
>>>> Python compiler writes them for you most of the time and doesn't make
>>>> you put ()'s at the end of the name
>>>
>>> I think Roy is referring to the fact that attribute access is implemented
>>> via __getattr__ / __getattribute__ /
>>> __setattr__ / __delattr__. From one point of view, he's absolutely correct
>>> - nearly all attributes are accessed via
>>> getters/setters in Python.
>>
>> Seems to me there is a difference between an underlying generic protocol for
>> data manipulation and "Python writing them
>> [getters/setters] for you".
>
> Why? When I write "foo.bar", a bunch of generic code gets run which
> figures out what value to return. If I don't like the generic behavior,
> I can write my own __getattrr__(), etc, and make it do whatever I want.
I don't yet know C++ so I can't speak to it.
In Python if you are writing your own __getattr__, etc., you are writing the underlying protocol itself. To write a
getter/setter you would just use
def get_soemthing(...)
def set_something(...)
or, even better
@property
def something(...)
Maybe, as Steven said, it's just a matter of degree: my understanding of getters/setters is that they are per
attribute, while __getattr__ will be called for every attribute not otherwise found, __setattr__ will be called for
every assignment, __delattr__ will be called for every deletion, and all that is assuming you haven't written your own
__getattribute__ and completely changed the rules for your class.
--
~Ethan~
More information about the Python-list
mailing list