【发布时间】:2016-10-11 22:34:57
【问题描述】:
我现在的位置是这样的:
class A(object):
def __init__(self, val):
self.x=val
self.y=42
# other fields
class B(object):
def __init__(self):
self.a=22
# other fields
class C(A,B):
def __init__(self, val):
super(C,self).__init__(val)
@property
def x(self):
# if A.x is None return a value that I can compute from A.y and B.a
# if A.x is not None return it
@x.setter
def x(self, val):
# set the field value
有时我只想手动为x 设置一个假定值,在这种情况下我会使用A。在其他情况下,我想使用一种更复杂的方法,该方法涉及根据组织成B 的信息计算A.x 的值。这段代码的想法是创建一个C 类,它看起来像一个A(就x 字段而言),但不需要手动设置该字段值,而是直接派生.
我想不通的是如何让C.x 属性以合理的方式覆盖A.x 字段。
【问题讨论】:
-
你是什么意思“以一种明智的方式”?您能否提供minimal reproducible example 说明您尝试对此进行的操作、您的预期以及发生了什么?
标签: python python-2.7 inheritance properties