Basj
Basj

Reputation: 46513

Delete a class property and replace it by a normal variable

Let's say we have this property:

import time

class Test:
    @property
    def dt(self):
        return time.time()

t = Test()
print(t.dt)  # 1590402868.9415174

In some instances of this class, I'd like to override this property and replace it by a constant instead.

t.dt = 1234

does not work: AttributeError: can't set attribute.

I've also tried with a setter:

@dt.setter
def dt(self, value):
    self.dt = value        

but then: RecursionError: maximum recursion depth exceeded.

Question: how to override/remove a property for an object instance, and replace it by a normal variable/attribute?

Upvotes: 0

Views: 36

Answers (1)

zanuda
zanuda

Reputation: 245

If I understand you correctly, something like this can help you:

class Test: 
    def __init__(self): 
        self._dt = None

    @property
    def dt(self):
        return self._dt if self._dt is not None else time.time()

    @dt.setter
    def dt(self, value):
        self._dt = value

    @dt.deleter
    def dt(self):
        self._dt = None

t = Test()
print(t.dt) #1590405187.1155756

t.dt = 1234 
print(t.dt) #1234

Or you can remove the attribute from the class itself:

t = Test()
delattr(t.__class__, 'dt')

t.dt = 1234
print(t.dt) #1234

In this case, you can not change your original code.

Upvotes: 1

Related Questions