[Tutor] Getting/setting attributes

lists lists at justuber.com
Wed Sep 22 00:32:51 CEST 2010


>
> My opinion - unless there is some verification or translation or action
> required it is better (easier, clearer) to just access and assign the
> attribute directly.

This makes sense. I guess my current way of doing it just reflects my
inexperience. At the moment I'm just fumbling this out so I guess I'm
being over-cautious.
>
>> I've been reading various ways of doing this, and the information seems a
>> little
>> contradictory.
>>
> Example, please?

Forgive me for any mistakes in this explanation, I'm still learning,
but as far as I can figure out, in some earlier versions (before 2.2
perhaps?) it wasn't possible to assign a decorator directly to a
method using the at sign, and it was necessary to do this elsewhere
within the class itself. I think this link explains what I mean:
http://docs.python.org/release/2.4.2/whatsnew/node6.html

It seems some tutorials I've been reading were written for this older syntax.

>>
>> I've muddled my way through the code below to try and force setting or
>> getting the 'address' attribute through the address method rather than
>> allowing direct access.
>
> Just because you have a getter and setter does not prohibit direct reference
> to _address.

I had read something about that. I wonder if the idea behind doing it
in the way I've shown is to help prevent the programmer from doing it
accidentally perhaps?
>>
>> class Computer(object):
>>
>>    def __init__(self):
>>        """instantiate the class with default values"""
>>        self.address = ""
>>
> I suggest (if you want to go the setter/getter route that you initialize
> _address, just in case someone tries to reference it without setting it.
>

Do you mean like:

class Computer(object):
   def __init__(self):
      address = ""
      self.address = address

Or am I missing the point?

Thanks for your time Bob,

Chris


More information about the Tutor mailing list