2011-05-01 62 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