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 little
contradictory.
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
919-636-4239
Chapel Hill NC
_______________________________________________
Tutor maillist - [email protected]
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor