Python 中 int 的子类化
我对 Python 中内置 int
类型的子类化感兴趣(我使用的是 v.2.5),但在初始化工作时遇到一些问题。
这是一些示例代码,应该相当明显。
class TestClass(int):
def __init__(self):
int.__init__(self, 5)
但是,当我尝试使用它时,我得到:
>>> a = TestClass()
>>> a
0
我期望结果为 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
int
是不可变的,因此创建后无法修改它,请使用__new__
代替int
is immutable so you can't modify it after it is created, use__new__
instead尽管正确,但当前答案可能并不完整。
例如
将 b 显示为整数,您可能希望它是一个 TestClass。
这是一个改进的答案,其中基类的函数被重载以返回正确的类型。
现在进行相同类型的测试
更新:
添加了 repr 和 str 示例,以便新类正确打印自身。即使 OP 使用 Python 2,也更改为 Python 3 语法以保持相关性。
04/22 更新:
我发现自己想在最近的两个项目中做类似的事情。我想要一个 Unsigned() 类型(即 xy,其中 x 为 0,y 为正值仍然为零)
我还想要一个类似 set() 的类型,能够以某种方式更新和查询。
上述方法有效,但重复且乏味。如果有一个使用元类的通用解决方案怎么办?
我找不到,所以我写了一篇。这仅适用于最近的Python(我猜是3.8+,在3.10上进行了测试)
首先,元类
创建新无符号类型的示例用法
示例的一些测试
以及@Kazz更新 :
来回答你的问题。虽然直接
int(u) * 0.2
会更简单,但这里有一个小的更新包装器来处理异常情况,例如 (Unsigned * float),它作为如何修改行为以匹配异常情况的示例。所需的子类行为,而不必单独重载每个可能的参数类型组合。
Though correct the current answers are potentially not complete.
e.g.
Shows b as an integer, where you might want it to be a TestClass.
Here is an improved answer, where the functions of the base class are overloaded to return the correct type.
Now the same sort of test
UPDATE:
Added repr and str examples so that the new class prints itself properly. Also changed to Python 3 syntax, even though OP used Python 2, to maintain relevancy.
UPDATE 04/22:
I found myself wanting to do something similar on two recent projects. One where I wanted an Unsigned() type (i.e. x-y, where x is 0 and y is positive is still zero)
I also wanted a set() like type the was able to be updated and queried in a certain way.
The above method works but it's repetitive and tedious. What if there was a generic solution using metaclasses?
I could not find one so I wrote one. This will only work in recent Python (I would guess 3.8+, tested on 3.10)
First, the MetaClass
An example usage to create a new Unsigned type
And some tests for the example
UPDATE for @Kazz:
To answer your question. Though it would be simpler to just
int(u) * 0.2
Here is a small updated wrapper to handle the exception case e.g. (Unsigned * float) that serves as an example of how to modify behavior to match the desired subclass behaviour without having to individually overload each possible combination of argument types.