是否可以在Python中定义一个类似整数的对象,它还可以存储实例变量? [英] Is it possible to define an integer-like object in Python that can also store instance variables?

查看:156
本文介绍了是否可以在Python中定义一个类似整数的对象,它还可以存储实例变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在数学运算或比较中使用时,是否可以在python中定义一个行为类似于普通整数的数据对象,但是也能够存储实例变量?

Is it possible to define a data object in python that behaves like a normal integer when used in mathematical operations or comparisons, but is also able to store instance variables?

换句话说,应该可以做以下事情:

In other words, it should be possible to do the following things:

pseudo_integer = PseudoInteger(5, hidden_object="Hello World!")
print(5 + pseudo_integer) # Prints "10"
print(pseudo_integer == 5) # Prints "True"
print(pseudo_integer.hidden_object) # Prints "Hello World!"


推荐答案

是的,确实如此。您可以创建自己的自定义类。 Python有许多神奇的方法来帮助你存档。

Yes, it is. You can create your own custom class. Python has many magic methods to help you archive that.

检查代码:

class PseudoInteger:
    def __init__(self, x, s):
        self.x = x
        self.s = s

    def __add__(self, num):
        return self.x + num

    def __eq__(self, num):
        return self.x == num


a = PseudoInteger(5, 'hello, world')
print(a + 3)
print(a == 5)
print(a == 2)

或者您可以从int继承,在创建实例后,您可以将属性分配给继承的int对象。您不能直接将属性赋给int,因为int不支持项目赋值:

Or you can just inherit from int, after creating an instance, you are able to assign attributes to the inherited int object. You can't assign attributes to int directly, because int does not support item assignment :

class PseudoInteger(int):
    pass

a = PseudoInteger(5)
a.hidden = 'hello, world'

print(a)
print(a == 5)
print(a + 3)
print(a.hidden)

这篇关于是否可以在Python中定义一个类似整数的对象,它还可以存储实例变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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