Pat*_*oki 3 python string int inheritance list
我想知道的继承是如何工作的int,list,string和其他稳定的类型.
基本上我只是继承了这样一个类:
class MyInt(int):
def __init__(self, value):
?!?!?
Run Code Online (Sandbox Code Playgroud)
我似乎无法弄明白,我如何设置它的设置值int?如果我这样做,self.value = value那么我的课将被这样使用:
mi = MyInt(5)
print(mi.value) # prints 5
Run Code Online (Sandbox Code Playgroud)
而我想像这样使用它:
mi = MyInt(5)
print(mi) # prints 5
Run Code Online (Sandbox Code Playgroud)
我该怎么做呢?
你可以子类化int,但因为它是不可变的,你需要提供一个.__new__()构造函数钩子:
class MyInt(int):
def __new__(cls, value):
new_myint = super(MyInt, cls).__new__(cls, value)
return new_myint
Run Code Online (Sandbox Code Playgroud)
您需要调用基础__new__构造函数以正确创建子类.
在Python 3中,您可以super()完全省略参数:
class MyInt(int):
def __new__(cls, value):
new_myint = super().__new__(cls, value)
return new_myint
Run Code Online (Sandbox Code Playgroud)
当然,这是假设你想操纵value传递到前super().__new__()或操纵new_myint返回之前多一些; 否则你也可以删除整个__new__方法,并将其实现为class MyInt(int): pass.