Skip to main content
 首页 » 编程设计

python之子类化 Python str 类并与纯字符串进行字符串比较

2025年05月04日20xxx_UU

我正在对字符串类 (BioSequence) 进行子类化,并将其也进行子类化 (Exon)。这些类应该与字符串数据和其他数据进行相等比较,如果与纯字符串类进行比较,它们应该是字符串比较和其他数据比较的综合结果。

编辑:我的意思是与纯字符串类进行比较时,它应该只是一个简单的字符串比较。对不起。

代码如下:

class BioSequence(str): 
    def __new__(cls, content, pos_s = 0, pos_e = -1): 
        return str.__new__(cls, content) 
 
    def __init__(self, content, pos_s = 0, pos_e = -1): 
        if pos_e == -1: 
            pos_e = pos_s + len(self) 
        self.pos_s_chrom = pos_s 
        self.pos_e_chrom = pos_e 
 
    def __eq__(self, otherSequence): 
        ''' Two sequnces are equal if pos_s_chrom, pos_e_chrom, and sequence itself is the same 
           or if otherSequence is just a string, do a normal string comparison 
        ''' 
        if isinstance(otherSequence, self.__class__): 
            return super.__eq__(self, otherSequence) and self.pos_s_chrom == otherSequence.pos_s_chrom and \ 
                self.pos_e_chrom == otherSequence.pos_e_chrom 
        else: # just a string comparison 
            #print('self:', self, type(str(self))) 
            #print('otherSequence:', otherSequence, type(otherSequence)) 
            return str.__eq__(self, otherSequence) 
 
    def __ne__(self, otherSequence): 
        return not self.__eq__(otherSequence) 
 
    def __str__(self): 
        className = type(self).__name__ 
        #return '[%s %s (s: %s, e: %s)]' % (className, self[:], self.pos_s_chrom, self.pos_e_chrom) 
        return '[%s %s (s: %s, e: %s)]' % (className, super().__getitem__(slice(None, None, None)), self.pos_s_chrom, self.pos_e_chrom) 
 
class Exon(BioSequence): 
    pass 
 
print(BioSequence('abcde', 10) == BioSequence('abcde', 10)) # True 
print(Exon('abcde', 10) == Exon('abcde', 10)) # True 
print(BioSequence('abcde', 10) == 'abcde') # True 
print(Exon('abcde', 10) == 'abcde') # True 
print(Exon(BioSequence('abcde', 10), 10) == 'abcde') # Want True, but False here 

我希望上面最后一行的结果是True;但是我无法让它工作。

不知何故 print(str.__eq__(Exon(BioSequence('abcde', 10), 10), 'abcde')) 产生 False。怎么会?

请您参考如下方法:

您的代码的主要问题是您的 str 子类实现了 __str__。坏主意。

你知道调用 str(whatever) 是如何委托(delegate)给 whatever.__str__ 的吗?发生这种情况是因为 str.__new__ 委托(delegate)给 whatever.__str__。当您调用 Exon(BioSequence(...), ...) 时,您的 __new__ 委托(delegate)给 str.__new__,委托(delegate)给 BioSequence.__str__。有一些 extra handling创建子类实例时,但字符串内容来自__str__.

您的外显子不包含 BioSequence 的字符,而是包含由 BioSequence 的 __str__ 方法返回的字符串的字符。这些字符不是 abcde,因此 __eq__ 比较自然会失败。