Skip to main content
 首页 » 编程设计

python之嵌套继承的问题——如何初始化父类

2024年10月24日9kevingrace

我对为什么下面的代码不起作用感到困惑:

class ComparativeAnnotatorConfiguration(HashableNamespace): 
    """ 
    Takes the initial configuration from the main driver script and builds paths to all files that will be produced 
    by these tasks. 
    """ 
    def __init__(self, args, gene_set, query_genome_files, target_genome_files, annot_files, transmap): 
        self.work_dir = os.path.join(args.workDir, 'comparativeAnnotator', gene_set.sourceGenome, gene_set.geneSet) 
        self.metrics_dir = os.path.join(args.outputDir, 'metrics') 
        self.tx_set_dir = os.path.join(args.outputDir, 'tm_transcript_set') 
        self.reference = self.Reference(args, query_genome_files, annot_files, self.work_dir) 
        self.transmap = self.TransMap(args, query_genome_files, target_genome_files, annot_files, transmap, self.work_dir) 
 
    class Reference(HashableNamespace): 
        """ 
        The args object that will be passed directly to jobTree 
        """ 
        def __init__(self, args, query_genome_files, annot_files, out_dir): 
            self.__dict__.update(vars(args.jobTreeOptions))  
            self.outDir = out_dir 
            self.refGenome = query_genome_files.genome 
            self.refFasta = query_genome_files.genome_fasta 
            self.sizes = query_genome_files.chrom_sizes 
            self.annotationGp = annot_files.gp 
            self.gencodeAttributes = annot_files.attributes 
            self.mode = 'reference' 
 
    class TransMap(Reference): 
        """ 
        The args object that will be passed directly to jobTree 
        """ 
        def __init__(self, args, query_genome_files, target_genome_files, annot_files, transmap, out_dir): 
            super(self.__class__, self).Reference.__init__(self, args, query_genome_files, annot_files, out_dir) 
            self.genome = target_genome_files.genome 
            self.psl = transmap.psl 
            self.refPsl = annot_files.psl 
            self.targetGp = transmap.gp 
            self.fasta = target_genome_files.fasta 
            self.mode = 'transMap' 

尝试实例化会导致错误:

AttributeError: 'super' object has no attribute 'Reference' 

我尝试了不同的版本,例如 super(TransMap, self).Reference.__init__ 和 Reference.__init__,但都给出了不同版本的 NameError 。这与此处概述的简单案例有何不同:

Using super() in nested classes

请您参考如下方法:

你想要这个:

super(ComparativeAnnotatorConfiguration.TransMap, self).__init__(...) 

这是 Python 类作用域规则的结果:类变量不在方法内部的作用域内。这不会因为你的“变量”本身就是一个类而改变。就 Python 而言,这完全是一回事。

在 Python 3 中,您可以编写更简单的代码:

super().__init__(...) 

这是升级的另一个原因。