Adding/removing instance members

Peter Otten __peter__ at web.de
Fri Jan 30 10:31:02 EST 2004


Ladvánszky Károly wrote:

> I understand instance members can be added to an object in a dynamic
> manner:
> 
> class Cc:
>   pass
> 
> oCc=Cc()
> oCc.x=10    # oCc now has a new member
> 
> What is the way to remove these instance members?
> Is it possible to add a new member whose name is given by a string?

You can delete an attribute like so:

del c.x

Use setattr/getattr/delattr() to set, get or delete attributes known only by
their name:

>>> class C: pass
...
>>> c = C()
>>> setattr(c, "x", 123)
>>> c.x
123
>>> getattr(c, "x")
123
>>> del c.x
>>> c.x
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: C instance has no attribute 'x'
>>> c.x = 123
>>> delattr(c, "x")
>>> c.x
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: C instance has no attribute 'x'

Peter



More information about the Python-list mailing list