3

我想知道继承如何用于int,liststring其他不可变类型。

基本上我只是继承一个这样的类:

class MyInt(int):
    def __init__(self, value):
        ?!?!?

我似乎无法弄清楚,我该如何设置它的设置值int?如果我这样做,self.value = value那么我的课程将像这样使用:

mi = MyInt(5)
print(mi.value) # prints 5

而我想像这样使用它:

mi = MyInt(5)
print(mi) # prints 5

我该怎么做呢?

4

1 回答 1

8

你可以子类化int,但是因为它是不可变的,你需要提供一个.__new__()构造函数钩子

class MyInt(int):
    def __new__(cls, value):
        new_myint = super(MyInt, cls).__new__(cls, value)
        return new_myint

您确实需要调用基本__new__构造函数来正确创建子类。

在 Python 3 中,您可以super()完全省略参数:

class MyInt(int):
    def __new__(cls, value):
        new_myint = super().__new__(cls, value)
        return new_myint

当然,这假设您想value在传入之前进行操作super().__new__()new_myint在返回之前进行更多操作;否则,您也可以删除整个__new__方法并将其实现为class MyInt(int): pass.

于 2013-02-26T09:52:47.290 回答