[Tutor] Class access rules

Cameron Simpson cs at cskk.id.au
Sun Mar 6 20:31:54 EST 2022


On 07Mar2022 11:33, Phil <phillor9 at gmail.com> wrote:
>I've imported the following class into several wxpython projects and 
>now into a tkinter project and now I'm wondering if I should modify 
>the class by adding setter and getter methods instead of directly 
>accessing the instance attributes. I know that Python will warn me 
>that I shouldn't access these attributes if I prefix them with an 
>underscore. My question is does it really matter or is simply just a 
>method to warn programmers who work in a group to not access those 
>attributes?

Warnings about access to ._foo attributes are just a reminder. The 
language itself doesn't care.  They're just a cue that the implementor 
of the class considers these attributes irrelevant to the _features_ 
provided by the class, and importantly: subject to change without 
warning.

So: if these attributes are basic features of the class (and ideally 
independent of each other, so that setting them directly should not lead 
to internal-to-the-class nonsense) and won't be going away just access 
them directly.

We don't do much setter/getter methods in Python. We do something make 
properties, which present as attributes to the outside and are 
implemented as getter methods with optional setter methods. Example:

    @property
    def post_pos(self):
        ''' The location "beyond" the rectangle implied by pos+size.
        '''
        return (self.pos[0] + self.size, self.pos[1] + self.size)

This makes an attribute whose value is _computed_ from self.pos and 
self.size. In this case there's no need for a setter method because you 
could try to set this to nonsense (eg different x/y "sizes", not 
expressible with your class' internal state).

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Tutor mailing list