【问题标题】:Delete a class property and replace it by a normal variable删除类属性并将其替换为普通变量
【发布时间】:2020-09-11 23:47:04
【问题描述】:

假设我们有这个属性:

import time

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

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

在这个类的某些实例中,我想覆盖这个property 并将其替换为一个常量。

t.dt = 1234

不起作用:AttributeError: can't set attribute

我也尝试过使用 setter:

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

然后:RecursionError: maximum recursion depth exceeded.

问题:如何覆盖/删除对象实例的property,并将其替换为普通变量/属性?

【问题讨论】:

    标签: python class properties attributes


    【解决方案1】:

    如果我对您的理解正确,以下内容可以帮助您:

    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
    

    或者您可以从类本身中删除该属性:

    t = Test()
    delattr(t.__class__, 'dt')
    
    t.dt = 1234
    print(t.dt) #1234
    

    在这种情况下,您不能更改原始代码。

    【讨论】:

      猜你喜欢
      • 2016-01-10
      • 2017-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-30
      • 1970-01-01
      • 2018-04-12
      相关资源
      最近更新 更多