[Tutor] Class access rules

Cameron Simpson cs at cskk.id.au
Sun Mar 6 23:08:32 EST 2022


On 07Mar2022 14:54, Phil <phillor9 at gmail.com> wrote:
>On 7/3/22 12:31, Cameron Simpson wrote:
>>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)
>
>Thanks Cameron, I read a brief explanation about the use the @property 
>decorator but couldn't see where I could use it. I'll continue with my 
>current line of class usage.

Thank's fine. Plenty of people don't use them much. I use them for 
things which are (a) secondary things the user will frequently want but 
which are derived from some more basic thing and (b) cheap, almost 
always O(1) time to compute (because they look like attributes and 
people expect attribute access to be essentially free).

An example from my POP3 mail fetcher:

    @property
    def netrc_entry(self):
        ''' The default `NetrcEntry` for this `ConnectionSpec`.
        '''
        machine = f'{self.user}@{self.host}:{self.port}'
        return NetrcEntry.get(machine)

    @property
    def password(self):
        ''' The password for this connection, obtained from the `.netrc` file
            via the key *user*`@`*host*`:`*port*.
        '''
        entry = self.netrc_entry
        return entry.password

The enclosing class represents a POP3 class whose credentials are kept 
in a netrc file. So I pretend there's direct access to the netrc entry, 
and direct access to the password. The former does a look up and the 
latter grabs the entry from the looked up netrc entry. From outside I 
start the POP3 stuff like this:

    self.client_begin()
    self.client_auth(self.conn_spec.user, self.conn_spec.password)

because the calling code just wants to send a username and password 
without caring where they come from.

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


More information about the Tutor mailing list