artsin
artsin

Reputation: 1494

Delete attribute from class instance python

I have example class:

class A():
    other_attribute = 2
    def __init__(self):
        setattr(A,"my_attribute",1)

a = A()

How can I delete my_attribute and other_attribute from instance?

PS. I edited code to better explain problem. For example I have class, which dynamically adds attributes

class A():
    def __init__(self, attribute_name, attribute_value):
        setattr(A, attribute_name, attribute_value)

a = A("my_attribute", 123)

I created my_attribute, in instance a, but then I do not need it anymore. But at other instances are other attributes, which I do not want to change.

Upvotes: 6

Views: 21112

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1122182

other_attribute and my_attribute are not an attributes on the instance. They are attributes on the class. You'd have to delete attributes from there, or provide an instance attribute with the same name (and a different value) to mask the class attribute.

Deleting the attributes from the class means that they'll not be available anymore on any instance.

You cannot 'delete' class attributes on individual instances. If an attribute is not to be shared by all instances, don't make them class attributes.

Upvotes: 9

Krystian
Krystian

Reputation: 211

other_attribute is shared by all instances of A, that means it is a part of

  A.__dict__ 

dictionary. You can do this for one instance of a class if you initialize an attribute in the constructor:

class A:
  def __init__(self):
    self.attrib = 2
    self.attrib2 = 3

a = A()
print "Before " + str(a.__dict__)
del a.__dict__["attrib"];
print "After " + str(a.__dict__)

Output is:

Before {'attrib2': 3, 'attrib': 2}
After {'attrib2': 3}

Upvotes: 6

Related Questions