[Tutor] Getting/setting attributes
vince at vinces.ca
Wed Sep 22 00:40:40 CEST 2010
On Tue, Sep 21, 2010 at 4:16 PM, bob gailer <bgailer at gmail.com> wrote:
> On 9/21/2010 5:06 PM, lists wrote:
>> Hi tutors,
>> I'm trying to each myself programming and come from a background in
>> system administration with some experience in scripting (so I'm very
>> new to it).
>> Currently I'm grappling with the concept of object orientating
>> programming and have a question about setting& getting attributes.
>> As I understand it, it makes most sense to set/get the attribute of an
>> object using a method rather than doing it directly.
> 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.
> I've been reading various ways of doing this, and the information seems a
>> Example, please?
> 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.
>> Does this make sense to you?
>> 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.
> @property # use the property.getter decorator on this method
>> def address(self):
>> return self._address
>> @address.setter #use the property.setter decorator on this method
>> def address(self, addrvalue):
>> self._address = addrvalue
>> computer1 = Computer()
>> computer1.address = "test"
>> print computer1.address
> Bob Gailer
> Chapel Hill NC
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
Here is a working example of what I think you are trying to achieve. In this
example the address is set via the setter
and some simple validation is there and the private var isn't available as
__address but get rewritten to _Computer__address (so not private but not
self.__address = None
# see note on private vars in Python
def address(self, value):
if value not in ("available", "criteria"):
self.__address = value
Hope that helps,
Sent from Ubuntu
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Tutor