简体   繁体   中英

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.

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.

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}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM