Adding attributes stored in a list to a class dynamically.
Brian Munroe
brian.e.munroe at gmail.com
Sun Sep 2 17:41:43 EDT 2007
On Sep 2, 11:46 am, al... at mac.com (Alex Martelli) wrote:
> If you want to pass the attributes list it's simpler to do that
> directly, avoiding *a and **k constructs. E.g.:
>
> def __init__(self, a, b, attrs):
> self.a = a
> self.b = b
> for attr in attrs:
> name, value = attr.split('=')
> setattr(self, name, value)
>
Alex:
Thanks for the example. I too had been wondering about this for a
while.
One question though, which I haven't been able to find the answer from
scouring the internet. What is the difference between calling
__setattr__ and setattr or __getattr__ and getattr, for that matter?
>From my example that follows, it doesn't seem to make a difference?
thanks
-- brian
class Person(object):
def __init__(self):
pass
def newAttribute(self,name,value=None):
setattr(self,name, value)
def newAttribute2(self,name,value=None):
self.__setattr__(name, value)
def dump(self):
for self.y in self.__dict__.keys():
yield self.y + "=" + getattr(self,self.y)
p1 = Person()
p1.newAttribute('fname','Brian')
p1.newAttribute('lname','Munroe')
p1.newAttribute2("mi","E")
for x in p1.dump():
print x
More information about the Python-list
mailing list