在 Python 中子类化 int [英] Subclassing int in Python

查看:29
本文介绍了在 Python 中子类化 int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Python 中的内置 int 类型的子类化很感兴趣(我使用的是 2.5 版),但是在初始化工作时遇到了一些麻烦.

这是一些示例代码,应该很明显.

class TestClass(int):def __init__(self):int.__init__(self, 5)

但是,当我尝试使用它时,我得到:

<预><代码>>>>a = 测试类()>>>一个0

我希望结果是 5.

我做错了什么?到目前为止,谷歌并没有太大帮助,但我不确定我应该搜索什么

解决方案

int 是不可变的,所以创建后不能修改,改用 __new__

class TestClass(int):def __new__(cls, *args, **kwargs):return super(TestClass, cls).__new__(cls, 5)打印测试类()

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆