Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 如何在python中重写属性函数的setter和getter?_Python 3.x_Oop_Inheritance_Overriding - Fatal编程技术网

Python 3.x 如何在python中重写属性函数的setter和getter?

Python 3.x 如何在python中重写属性函数的setter和getter?,python-3.x,oop,inheritance,overriding,Python 3.x,Oop,Inheritance,Overriding,我使用property函数创建成员,但当我试图重写这些属性的setter和getter时,它总是引用父类的setter和getter: class A(): def evaluate(self): return 'A' value = property(evaluate) class B(A): def evaluate(self): return 'B' b = B() print(b.value) # I get 'A' 我尝试将

我使用property函数创建成员,但当我试图重写这些属性的setter和getter时,它总是引用父类的setter和getter:

class A():
    def evaluate(self):
        return 'A'
    value = property(evaluate)

class B(A):
    def evaluate(self):
        return 'B'

b = B()
print(b.value) # I get 'A'
我尝试将值成员的定义放入父级的构造函数中,例如:

self.value = property(self.evaluate)
但是当访问对象的值时,它返回的是属性对象,而不是实际值,例如:“a”或“B”

<property object at 0x7fecd01a88b8>

我知道如何解决这个问题,但我想知道是否可以使用属性函数/decorator解决这个问题,而不需要代码重复。

问题是,表达式propertyevaluate将属性绑定到执行类主体时作用域中的求值函数。要执行您想要的操作,您必须延迟访问evaluate,直到使用该属性

这是可行的,但如果我们知道您为什么要这样做,可能有更好的方法:

class A():
    def evaluate(self):
        return 'A'
    value = property(lambda self: self.evaluate())

class B(A):
    def evaluate(self):
        return 'B'

b = B()
print(b.value) # prints 'B'
如果您只想为a或B返回不同的常量字符串,则根本不需要属性:

class A():
   value = 'A'

class B(A):
   value = 'B'

b = B()
print(b.value)
如果您确实需要一个属性,那么只需在子类中重新定义该属性:

class A():
   @property
   def value(self):
       return 'A'

class B(A):
   @property
   def value(self):
       return 'B'

b = B()
print(b.value)

第一个解决方案的可能副本是我正在寻找的。