Re: Newbie: Why doesn't this work
- From: Tim Chase <python.list@xxxxxxxxxxxxxxxxx>
- Date: Mon, 31 Dec 2007 11:39:01 -0600
A couple items of note:
class Person:
This should be "class Person(object)" to take advantage of some
of the features that new-style classes offer...particularly in
this case.
def __init__(self, fName="", lName=""):
self.__fName = fName
self.__lName = lName
def __getattr__(self, attr):
if attr == "name":
return self.__fName + " " + self.__lName
def __setattr__(self, attr, value):
# this assumes that value is a tuple of first and last name
if attr == "name":
self.__fName, self.__lName = value
if the attr isn't "name", no default behavior gets called here.
The common way, with new-style classes is to add
else:
parent(Person, self).__setattr__(attr, value)
Do be aware that this has some odd behaviors when what you put in
and what you get out are different types:
Traceback (most recent call last):p1.name = ("Joe", "Smith")
p2.name = p1.name
File "x.py", line 22, in ?
p2.name = P.name
File "x.py", line 13, in __setattr__
self.__fName, self.__lName = value
ValueError: too many values to unpack
(slightly munged traceback as it actually came from the test
input file rather than the interactive prompt)
-tim
.
- Follow-Ups:
- Re: Newbie: Why doesn't this work
- From: ct60
- Re: Newbie: Why doesn't this work
- References:
- Newbie: Why doesn't this work
- From: ct60
- Newbie: Why doesn't this work
- Prev by Date: Re: Newbie: Why doesn't this work
- Next by Date: What's the limit of variables size in pyhton?
- Previous by thread: Re: Newbie: Why doesn't this work
- Next by thread: Re: Newbie: Why doesn't this work
- Index(es):