本文介绍了在Python中重载int()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说我在Python 3中有一个基本类,它代表一些数字类型的数据类型。我想让它这样当我有一个实例,x,这个类,我可以调用int(x),并让它调用我的转换函数返回整数部分。
Say I have a basic class in Python 3 which represents some number-like data-type. I want to make it so when I have an instance, x, of this class I can call int(x) and have it call my conversion function to return the integer portion.
我确定这很简单,但我似乎不知道该怎么做。
I'm sure this is simple, but I can't seem to find out how to do it.
推荐答案
覆盖 __ int __
魔法方法,如下例所示:
You override the __int__
magic method as per the following example...
class Test:
def __init__(self, i):
self.i = i
def __int__(self):
return self.i * 2
t = Test(5)
print( int(t) )
# 10
这篇关于在Python中重载int()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!