繁体   English   中英

从父 class 调用任意子属性?

[英]Call an arbitrary child attribute from a parent class?

我想“标记”派生 class 的属性(其他方面相同),以便父 class 的方法可以使用特定的方法。

在这个例子中,我正在构建神经元模型,每个神经元都由“区域”组成,而“区域”又由“段”组成。 有一个 neuron_region 父 class。 神经元区域父 class 有一个“连接”方法,它将一个段连接到另一个段(作为参数传递给它 - 在另一个神经元上)。 需要有一种方法来标记派生的 class 中的哪个段需要连接。 什么是一种优雅的方式来做到这一点?

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'

做可能可行的最简单的事情——也许是这样的:

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。

你可以做

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

在这里,您甚至有两种方法:

  1. 子 class 定义了一个conn_attr属性来确定哪个属性是用于连接的。 它用于基础 class 中的connected属性。 如果seg1分别。 seg2变化,这是 go 的方式。

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

在这两种方法中,父 class 只使用self.connected

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM