继承自不可变类型 [英] Inheriting from immutable types
问题描述
我想知道继承如何适用于 int
, list
, string
和其他不可变类型。
I'd like to know how inheritance works for int
, list
, string
and other immutable types.
基本上我只是继承了这样一个类:
Basically I'd just inherit a class like this:
class MyInt(int):
def __init__(self, value):
?!?!?
我似乎无法弄清楚,如何设置为<$设置的值C $ C> INT ?如果我 self.value = value
那么我的课程将被这样使用:
I can't seem to figure out, how do I set the value like it's set for int
? If I do self.value = value
then my class will be used like this:
mi = MyInt(5)
print(mi.value) # prints 5
虽然我想这样使用它:
mi = MyInt(5)
print(mi) # prints 5
我该怎么做?
推荐答案
你可以继承 int
,但因为它是 immutable 你需要提供一个 .__ new __()
constructor hook :
You can subclass int
, but because it is immutable you need to provide a .__new__()
constructor hook:
class MyInt(int):
def __new__(cls, value):
new_myint = super(MyInt, cls).__new__(cls, value)
return new_myint
您需要调用基本 __ new __
构造函数来正确创建子类。
You do need to call the base __new__
constructor to get your subclass properly created.
在Python 3中,您可以省略 supe的参数r()
一共:
In Python 3, you can omit the arguments to super()
altogether:
class MyInt(int):
def __new__(cls, value):
new_myint = super().__new__(cls, value)
return new_myint
当然,这假设你想要在传入 super().__ new __()$ c $之前操纵
值
c>或在返回之前操纵 new_myint
更多;否则你也可以删除整个 __ new __
方法,并将其实现为类MyInt(int):传递
。
Of course, this assumes you wanted to manipulate value
before passing in to super().__new__()
or manipulate new_myint
some more before returning; otherwise you may as well remove the whole __new__
method and just implement this as class MyInt(int): pass
.
这篇关于继承自不可变类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!