[Tutor] Getting/setting attributes

lists lists at justuber.com
Tue Sep 21 23:06:50 CEST 2010


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. I've been reading
various ways of doing this, and the information seems a little
contradictory.

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.

Does this make sense to you?

Ta, Chris.

class Computer(object):

   def __init__(self):
       """instantiate the class with default values"""
       self.address = ""

   @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


More information about the Tutor mailing list