Newbie: Why doesn't this work
ct60 at aol.com
ct60 at aol.com
Mon Dec 31 11:56:02 EST 2007
Hi Python Community:
Despite my new-ness to Python I have alreadhy been able to do some (I
think) amazing things. It is a truly elegant and smart language.
Yet, I can not seem to get a handle on something simple.
I would like to make a class which has private varaiables fName and
lName. It should have a property "name" which can get or set a name.
Something like as follows:
class Person:
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
P = Person()
P.name = ("Joe", "Smith")
print P.name
This fails with the following note:
>>>
Traceback (most recent call last):
File "C:\Python\testObject.py", line 20, in <module>
print P.name
File "C:\Python\testObject.py", line 8, in __getattr__
return self.__fName + " " + self.__lName
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
I don't understand why this fails. I thought perhaps I need to make
the __getattr__ function like this
def __getattr__(self, attr):
if attr == "name":
return self.__fName + " " + self.__lName
elif attr == "__fName":
return self.__fName
elif attr == "__lName":
return self.__lName
But that still fails.
Can someone please tell me what I am doing wrong?
Thansk in advance,
Chris (ct60 at aol.com)
More information about the Python-list
mailing list