如何在return语句中返回已定义子类的新对象

时间:2017-11-03 17:46:40

标签: python class return

我试图在return语句中获取已定义类的新对象,但是在使用return语句时遇到了困难。我应该得到的是一个新对象,通过在同一个return语句中调用构造函数 传递那些需要构造函数的参数。考虑到每个类的构造函数是类的名称。

这就是我到目前为止所做的:

def complementary(self):
     complementary = ''.join([DNA.bases_complementary[base] for base in self.get_sequence()])
     return complementary

但它只返回一个显而易见的字符串,但可以将此字符串作为子类DNA的新对象返回(超类是SEQUENCE)。 我的SuperClass是这样的:

class SEQUENCE:
    def __init__(self, sequence):
        self.__sequence = sequence
        length = len(sequence) 
    def __str__(self):
        st =  'The introduced sequence is: {0}\n'.format(self.__sequence)
        st = st + 'The length of the sequence is: {0}\n'.format(len(self.__sequence))
        return st

    def get_sequence(self):
        return self.__sequence

我的DNA子类是这样的:

class DNA(SEQUENCE):
    bases = {'A','T', 'C','G'} 
    complementary_bases = {'A':'T', 'T':'A', 'C':'G','G':'C'}
    transcription = {'A':'U', 'T':'A', 'C':'G','G':'C'}

    def __init__(self, sequence):
        super().__init__(sequence)
        self.__length = len(sequence)
        bases = {'A','T','C','G'}
        sequence_set = set(sequence)
        if sequence_set <= bases: 
            print('The introduced sequence is', sequence, 'with the following length',len(sequence))
        else: 
            print('INCORRECT DNA SEQUENCE')
            raise NameError('SequenceError')

1 个答案:

答案 0 :(得分:0)

试试这个:

return DNA(complementary)