Adding/removing instance members

Discussion in 'Python' started by Ladvánszky Károly, Jan 30, 2004.

  1. 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?

    Thanks on any help,

    Károly
     
    Ladvánszky Károly, Jan 30, 2004
    #1
    1. Advertising

  2. Ladvánszky Károly

    Peter Otten Guest

    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
     
    Peter Otten, Jan 30, 2004
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. JFCM
    Replies:
    4
    Views:
    5,740
  2. CoolPint
    Replies:
    8
    Views:
    989
    Jeff Schwab
    Dec 14, 2003
  3. hdixon
    Replies:
    3
    Views:
    648
    hdixon
    Jul 9, 2006
  4. Daz
    Replies:
    5
    Views:
    583
  5. Raj Singh
    Replies:
    2
    Views:
    200
    Rick DeNatale
    May 29, 2008
Loading...

Share This Page