Adding attributes stored in a list to a class dynamically.

Brian Munroe brian.e.munroe at
Sun Sep 2 23:41:43 CEST 2007

On Sep 2, 11:46 am, al... at (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)


Thanks for the example.  I too had been wondering about this for a

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?


-- brian

class Person(object):

	def __init__(self):

	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()

for x in p1.dump():
	print x

More information about the Python-list mailing list