[Tutor] self.name is calling the __set__ method of another class

Mats Wichmann mats at wichmann.us
Thu May 2 12:10:23 EDT 2019


On 5/2/19 9:25 AM, Arup Rakshit wrote:
> On 30/04/19 6:34 AM, David L Neil wrote:
>> As Steven explained, this is a complex environment where only those
>> with a good understanding of the meta abstractions would even want to
>> play (IMHO). Perhaps you would be better served by actually writing
>> some Python applications, and with such experience under-your-belt,
>> adding these 'advanced knowledge' ideas at some later time, if/when
>> needed?)
> 
> Thanks David for suggesting this. I am going to do that, writing an web
> application using Python Flask. It feels more easier than battling with
> such frustrated abstractions. :) I don't know why python exposed so many
> things, and getter/setter goes wild in that respect.  It was not thathard in the other languages(Ruby, JS).

So let me make this comment: some of us (yeah, I'm guilty of this) like
to expose the underlying details when talking about something.  In my
case, I do that because it's how I myself learn - if the details make
beautiful sense, then the "normal way" complete with syntactic sugar
doesn't feel like a mystery and I'm much happier. Does that mean
everybody needs those details up front? Absolutely not. PyCon talks have
a high risk of doing this - great material, usually, but they got
accepted as talks because they are "revealing secrets". Attendees
already knew how to use the feature but come back from the conference
going "now I understand so much better" and so got their money's worth.

In normal everyday use, getters and setters in Python are simple.

(a) don't use them unless you actually need them, which is rarely - this
isn't C++, Java, etc. where you're supposed to encapsulate everything.
(b) if you do need them, "wrap" a regular attribute access in your class
definition.

So I wouldn't write this:

class C:
    def __init__(self, x):
        self.__x = x

    def get_x(self):
        return self.__x

    def set_x(self, x):
        self.__x = x

# But this:

class C:
    def __init__(self, x):
        self.x = x


Now if you later found that 'x' needed to be more complex (in this
trivial example, x is only allowed to be between 0 and 100), we can add
property decorators which provide some sort of encapsulation, but leaves
the same API - so the retrofit doesn't break clients:

class C:
    def __init__(self, x):
        self.x = x

    @property
    def x(self):
        return self.__x

    @x.setter
    def x(self, x):
        if x < 0:
            self.__x = 0
        elif x > 100:
            self.__x = 100
        else:
            self.__x = x



More information about the Tutor mailing list