【问题标题】:How to return a new object of a defined subclass in return statement如何在 return 语句中返回已定义子类的新对象
【发布时间】:2018-04-16 12:51:18
【问题描述】:

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

这是我目前所拥有的:

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

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

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')

【问题讨论】:

  • complimentaria 的返回字符串示例是什么?

标签: python class return


【解决方案1】:

试试这个:

return DNA(complementary)

【讨论】:

  • 它返回这个:引入的序列是'sequence'序列的长度是'length' <__main__.dna object at>,就我而言,返回一个DNA对象但是句子“ <__main__.dna object at>” 究竟是什么意思?
  • <__main__.dna object at> 是您想要的对象,“引入的序列是'sequence',序列的长度是'length'”是您编码时该对象的输出在 __init__()
  • 如果 x = DNA('ACTGGT') 并且我调用 x.complentary() 它将新对象作为 DNA 返回,但是当我调用 x.get_sequence() 时它返回前一个对象,我的意思是它返回原始 x 而不是互补序列。这正常吗?
猜你喜欢
  • 2021-11-25
  • 1970-01-01
  • 2013-03-24
  • 2019-04-01
  • 2021-02-06
  • 2014-01-17
  • 1970-01-01
  • 2019-07-31
  • 1970-01-01
相关资源
最近更新 更多