子类化内置类型 - Python 2和3

时间:2014-02-26 10:29:33

标签: python python-2.7 python-3.x

我的代码如下所示:

class Token(object):
    '''
    Resulting from parse
    '''
    def __new__(cls,text,begin,end,*args,**kargs):
        self = super(Token,cls).__new__(cls,*args,**kargs)
        return self

    def __init__(self,text,begin,end,*args,**kargs):
        super(Token,self).__init__(*args,**kargs)
        self.text = text
        self.begin = begin
        self.end = end

class List(Token,list):
    pass

class Str(Token,str):
    pass

class Int(Token,int):
    pass

s = Str('hey there',0,3,'hey there'[0:3])
print(s)

x = Int('55 12',0,2,'55 12'[0:2])
print(x)

基本上我想做的是轻松创建只是普通Python类型的类型,但是需要一些额外的信息。

Python 2似乎没有上面的代码,但Python 3抱怨

Traceback (most recent call last):
  File "simple.py", line 71, in <module>
    s = Str('',1,2,'hey')
  File "simple.py", line 12, in __init__
    super(Token,self).__init__(*args,**kargs)
TypeError: object.__init__() takes no parameters

我认为如果我做了像

这样的事情,口译员会很高兴
class List(list):
    def __init__(self,text,begin,end,*args,**kargs):
        list.__init__(*args,**kargs)

但是这意味着我必须为我想要制作的每一个新课程重复类似的事情......我宁愿保持相对干燥......

我应该采用'正确'的方式处理这种情况,以便Python 2和Python 3都满意吗?

1 个答案:

答案 0 :(得分:1)

最好的办法是在这里使用异常处理:

def __init__(self,text,begin,end,*args,**kargs):
    try:
        super(Token,self).__init__(*args,**kargs)
    except TypeError:
        # Python 3 and the mixed in type is immutable.
        # Ignoring this is fine, `__new__` took care of this.
        pass
    self.text = text
    self.begin = begin
    self.end = end