如何从父类调用任意子类属性?
我想给一个派生类的属性“标记”,这些属性本身是一样的,这样父类的方法就可以使用特定的一个。
在这个例子中,我正在构建神经元的模型,每个神经元由“区域”组成,而这些区域又由“片段”构成。这里有一个名为 neuron_region 的父类。这个 neuron_region 父类有一个“连接”方法,可以把一个片段连接到另一个片段(这个片段作为参数传递给它,可能是在另一个神经元上)。我需要一种方法来标记在派生类中需要连接的片段。有没有什么优雅的方式来做到这一点?
class neuron_region(object):
def connect(external_segment)
#connect segment 1 or segment 2 to external_segment,
#depending on which one is the right attribute
class child1(parent):
#mark segment 1 as the segment to which to connect#
self.seg1='segment 1'
self.seg2='segment 2'
class child2(parent):
self.seg1='segment 1'
#mark segment 2 as the segment to which to connect#
self.seg2='segment 2'
2 个回答
0
你可以这样做:
class neuron_region(object):
def connect(external_segment)
#connect segment 1 or segment 2 to external_segment,
#depending on which one is the right attribute
# the following can/must be omitted if we don't use the conn_attr approach
@property
def connected(self):
return getattr(self, self.conn_attr)
class child1(parent):
seg1 = 'segment 1'
seg2 = 'segment 2'
#mark segment 1 as the segment to which to connect#
conn_attr = 'seg1'
# or directly - won't work if seg1 is changed sometimes...
connected = seg1
class child2(parent):
seg1 = 'segment 1'
seg2 = 'segment 2'
#mark segment 2 as the segment to which to connect#
conn_attr = 'seg2'
# or directly - won't work if seg2 is changed sometimes...
connected = seg2
这里有两种方法:
子类定义一个叫做
conn_attr
的属性,用来决定哪个属性是用来连接的。这个属性会在父类的connected
属性中使用。如果seg1
或者seg2
有时会变化,这种方法比较合适。子类直接定义
connected
。这样就不需要一个转发的属性,但这种方法只在所用的属性不发生变化时有效。
在这两种方法中,父类只需要使用 self.connected
。
1
做最简单的事情,尽可能地让它有效 - 也许可以这样理解:
SEGMENTS = (SEGMENT_1, SEGMENT_2) = range(2)
class NeuronRegion(object):
def __init__(self):
self.connection = [None, None]
self.chosen = 0
def choose(self, segment):
assert segment in SEGMENTS
self.chosen = segment
def connect(other_neuron_region):
# remember to reset those to None when they're not needed anymore,
# to avoid cycles that prevent the garbage collector from doing his job:
self.connection[self.chosen] = other_neuron_region
other_neuron_region.connection[other_neuron_region.chosen] = self
class Child1(NeuronRegion):
''' other stuff '''
class Child2(NeuronRegion):
''' other stuff '''
[编辑] 我得承认我不是很喜欢这样做,但在我看来,它确实达到了你想要的效果。