从子类中已实例化的父级检索所有函数和属性

时间:2019-01-18 16:24:04

标签: python-3.x inheritance

我正在尝试做this:用父类的实例初始化子类。

genomic_feature_instance是实例化的,并且包含以下内容:

  

{'name':'ENSG00000223972.5','type':'gene','iv':,'source':'HAVANA',   'score':'。','frame':'。','attr':{'ID':'ENSG00000223972.5',   'gene_id':'ENSG00000223972.5','gene_type':   'transcribed_unprocessed_pseudogene','gene_status':'KNOWN',   'gene_name':'DDX11L1','leve l':'2','havana_gene':   'OTTHUMG00000000961.2'}}

我想创建一个自定义/子实例来操纵此类genomic_feature_instance中的属性和函数。

 aCustomGenomicFeature = CustomGenomicFeature(genomic_feature_instance,'kikou')

这是我所做的,但是我想使用super()从此genomic_feature(GenomicFeature实例)继承所有属性值

class CustomGenomicFeature(GenomicFeature):

    def __init__(self,genomic_feature_instance,kikou):

        # call parent constructor to set name and color 
        self.genomic_feature = genomic_feature_instance
        # Subclass-specific stuff follows
        self.kikou=kikou

1 个答案:

答案 0 :(得分:0)

使用__dict __。update

我宁愿使用__dict__而不是super,因为super不会帮助您复制父对象的属性值。因此,您可以执行以下操作:

class A():
    def __init__(self):
        self.x = 1

class B(A):
    def __init__(self, a):
        super(B, self).__init__()
        self.__dict__.update(a.__dict__)

a = A()
b = B(a)

print(b.x)  # displays '1'

a.x = 3
b2 = B(a)

print(b2.x)  # displays '3'. Without the __dict__update, it would return '1'

这样,您可以设置父类具有的每个属性,而无需修改父类不具有的子类的属性。

在您的情况下:

class CustomGenomicFeature(GenomicFeature):

    def __init__(self,genomic_feature_instance,kikou):

        super().__init__()
        self.__dict__.update(genomic_feature_instance.__dict__)

        # Subclass-specific stuff follows
        self.kikou=kikou

有构图

另一种方法(也许更干净)是使用组成而不是继承:

class CustomGenomicFeature(GenomicFeature):

    def __init__(self,genomic_feature_instance,kikou):

        # keep ref to the genomic_feature_instance
        self._genomic_feature = genomic_feature_instance

        # Subclass-specific stuff follows
        self.kikou=kikou

    @property
    def name(self):
        return self._genomic_feature.name

更多: