从不可变类型继承[重复]
问题内容:
这个问题已经在这里有了答案 :
从str或int继承 (5个答案)
3年前关闭。
我想知道的继承是如何工作的int
,list
,string
和其他稳定的类型。
基本上我只会继承这样的类:
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
我该怎么做呢?
问题答案:
您可以子类化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
。