art*_*sin 2 python oop attributes class
我有示例类:
class A():
other_attribute = 2
def __init__(self):
setattr(A,"my_attribute",1)
a = A()
Run Code Online (Sandbox Code Playgroud)
如何删除my_attribute并other_attribute从实例?
PS.我编辑了代码以更好地解释问题.例如,我有类,它动态添加属性
class A():
def __init__(self, attribute_name, attribute_value):
setattr(A, attribute_name, attribute_value)
a = A("my_attribute", 123)
Run Code Online (Sandbox Code Playgroud)
我my_attribute在实例中创建了a,但后来我不再需要它了.但在其他情况下是其他属性,我不想改变.
other_attribute并且my_attribute不是实例上的属性.它们是班级的属性.您必须从那里删除属性,或提供具有相同名称(和不同值)的实例属性来掩盖类属性.
从类中删除属性意味着它们在任何实例上都不再可用.
您无法在各个实例上"删除"类属性.如果所有实例都不共享属性,请不要将它们设为类属性.
小智 5
other_attribute 被 A 的所有实例共享,这意味着它是 A 的一部分
A.__dict__
Run Code Online (Sandbox Code Playgroud)
字典。如果在构造函数中初始化属性,则可以对类的一个实例执行此操作:
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__)
Run Code Online (Sandbox Code Playgroud)
输出是:
Before {'attrib2': 3, 'attrib': 2}
After {'attrib2': 3}
Run Code Online (Sandbox Code Playgroud)