我想'标记'派生类的属性(在其他方面是相同的),以便父类的方法可以使用特定的属性。
在这个例子中,我正在构建神经元模型,每个神经元由“区域”组成,而“区域”又由“区段”组成。有一个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'
答案 0 :(得分: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 '''
<强> [编辑] 强> 我不得不承认我不喜欢这个,但它确实按照你的要求行事,IMO。
答案 1 :(得分: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
。