Search code examples
pythonpython-3.xinstancedelobject-properties

How to delete property?


class C():
    @property
    def x(self):
        return 0
delattr(C(), 'x')
>>> AttributeError: can't delete attribute

I'm aware del C.x works, but this deletes the class's property; can a class instance's property be deleted?


Solution

  • Refer to this answer; TL;DR, it's not about properties, but bound attributes, and x is bound to the class, not the instance, so it cannot be deleted from an instance when an instance doesn't have it in the first place. Demo:

    class C():
        pass
    
    @property
    def y(self):
        return 1
    
    c = C()
    c.y = y
    del c.y  # works
    c.y
    
    >>> AttributeError: 'C' object has no attribute 'y'