在Python中对int进行子类化 [英] Subclassing int in Python
本文介绍了在Python中对int进行子类化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有兴趣在Python中继承内置的 int
类型(我正在使用v.2.5),但在初始化工作时遇到一些麻烦。 / p>
以下是一些示例代码,应该相当明显。
class TestClass(int):
def __init __(self):
int .__ init __(self,5)
然而,当我尝试使用它时,我得到:
>>> a = TestClass()
>>> a
0
我希望结果是 5
。
我做错了什么?到目前为止,谷歌还不是很有帮助,但我不确定我应该搜索什么
解决方案
int
是不可变的,所以你不能在创建后修改它,使用 __ new __
而不是
class TestClass(int):
def __new __(cls,* args,** kwargs):
return super(TestClass, cls).__ new __(cls,5)
print TestClass()
I'm interested in subclassing the built-in int
type in Python (I'm using v. 2.5), but having some trouble getting the initialization working.
Here's some example code, which should be fairly obvious.
class TestClass(int):
def __init__(self):
int.__init__(self, 5)
However, when I try to use this I get:
>>> a = TestClass()
>>> a
0
where I'd expect the result to be 5
.
What am I doing wrong? Google, so far, hasn't been very helpful, but I'm not really sure what I should be searching for
解决方案
int
is immutable so you can't modify it after it is created, use __new__
instead
class TestClass(int):
def __new__(cls, *args, **kwargs):
return super(TestClass, cls).__new__(cls, 5)
print TestClass()
这篇关于在Python中对int进行子类化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文