用常规属性覆盖描述符

2024-05-14 09:36:27 发布

您现在位置:Python中文网/ 问答频道 /正文

是否可以通过派生类中的常规属性重写基类中的属性,如下所示:

class A(object):
     @property
     def x(self):
          return self._x

     @x.setter
     def x(self, y):
          self._x = y

 class B(A):
     def __init__(self, y):
          self.x = y #the descriptor methods are not called and
                     #"x" is a regular attribute in the object dict.

我问这个问题的原因是因为我有一个复杂的基类,其中一个描述符属性通常执行复杂的计算。但是,在其中一个派生类中,返回的值很小,必须使用另一个描述符而不仅仅是常规存储属性进行重写似乎是一种浪费


Tags: theselfreturn属性objectinitdefproperty
1条回答
网友
1楼 · 发布于 2024-05-14 09:36:27

您只需在B中重新声明x

class A(object):
    @property
    def x(self):
        print("calculating x...") 
        return self._x

    @x.setter
    def x(self, y):
        print('setting x...')
        self._x = 10*y

class B(A):
    x = None

    def __init__(self, y):
        self.x = y  #the descriptor methods are not called and
                    #"x" is a regular attribute in the object dict.

b = B(3)
print(b.x)
# 3

相关问题 更多 >

    热门问题