gpt4 book ai didi

python - 一种优雅的重载 Python 类属性的方法

转载 作者:太空宇宙 更新时间:2023-11-03 14:33:15 26 4
gpt4 key购买 nike

考虑一个基类:

class A(object):
def __init__(self, x):
self._x = x

def get_x(self):
#...
return self._x

def set_x(self, x):
#...
self._x = x

x = property(get_x, set_x)

和派生类:

class B(A):
def set_x(self, x):
#...
self._x = x**2

x = property(A.get_x, set_x)

是否有一种优雅的方法可以在 B 类中重载 set_x(),而无需重新声明它和属性 x?谢谢。

最佳答案

添加一个额外的间接层(即使用钩子(Hook)):

class A(object):
def __init__(self, x):
self._x = x

# Using a _get_hook is not strictly necessary for your problem...
def _get_hook(self):
return self._x
def get_x(self):
return self._get_hook()

# By delegating `set_x` behavior to `_set_hook`, you make it possible
# to override `_set_hook` behavior in subclass B.
def _set_hook(self, x):
self._x=x
def set_x(self, x):
self._set_hook(x)

x = property(get_x, set_x)

class B(A):
def _set_hook(self, x):
print('got here!')
self._x = x**2

b=B(5)
b.x=10
# got here!
print(b.x)
# 100

对于现代版本的 Python,您还可以使用 @property 装饰器:

class A(object):

@property
def x(self):
return self._get_hook()

@x.setter
def x(self, x):
self._set_hook(x)

关于python - 一种优雅的重载 Python 类属性的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6870616/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com