2011-05-01 54 views
0

我想“标记”派生类的属性(它们在其他方面是相同的),以便父类的方法可以使用特定的类。从父类中调用任意的子属性?

在这个例子中,我构建了神经元模型,每个神经元由“区域”组成,而“区域”又由“片段”组成。有一个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

我很难理解你想要做什么! :( – 2011-05-01 20:46:25

+0

@Deniz - 我已经改进了一些代码,使其更加清晰,评论是我想“能够做到的。基本上每个派生类将有许多段,但只有其中一个应该作为其他部分连接到的那个。 – 2011-05-01 21:00:10

回答

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。

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 

在这里,你甚至有2方法:

  1. 子类中定义了一个conn_attr属性,以确定哪个属性是用于连接的一个。它用于基类中的connected属性。如果seg1 resp。 seg2不时发生变化,这是要走的路。

  2. 子类直接定义connected。因此,不需要重定向属性,但只有在没有使用的属性发生更改时才有效。

在这两种方法中,父类仅使用self.connected