On Tue, Sep 21, 2010 at 4:16 PM, bob gailer <[email protected]> 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 >> 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 > Hello Bob, 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 obvious) class Computer(object): def __init__(self): self.__address = None # see note on private vars in Python http://docs.python.org/tutorial/classes.html?highlight=private#private-variables @property def address(self): return self.__address @address.setter def address(self, value): if value not in ("available", "criteria"): raise AttributeError("Nope") self.__address = value Hope that helps, Vince Spicer -- Sent from Ubuntu
_______________________________________________ Tutor maillist - [email protected] To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
