更改Python对象的表示形式

时间:2015-08-07 20:52:58

标签: python object

在Python中,数据类型(如int,float)既代表值,又具有一些内置属性/函数/等:

In [1]: a = 1.2

In [2]: a
Out[2]: 1.2

In [3]: a.is_integer()
Out[3]: False

是否可以在Python中重现此行为,例如定义一个类:

class Scalar:
    def __init__(self, value)
        self.value = value

    # other code ....

s = Scalar(1.2)

我可以s返回1.2(而不是键入s.value),并执行a = s - >等操作a = 1.2?我最接近这种行为的是添加类似:

def __getitem__(self, key=None):
    return self.value

并使用a = s[()],但这看起来不太好。

2 个答案:

答案 0 :(得分:4)

  

我可以返回1.2(而不是键入s.value)

在控制台中?然后实现__repr__方法。

  

a = s - > a = 1.2

为避免使用a = s.value,您可以实施__call__并调用该对象:

>>> class Scalar:
...     def __init__(self, value):
...         self.value = value
...     def __repr__(self):
...         return str(self.value)
...     def __call__(self):
...         return self.value
... 
>>> s = Scalar(1.2)
>>> s
1.2
>>> a = s()
>>> a
1.2

查看有关data model on emulating numeric types

的文档

例如:

class Scalar:
    def __init__(self, value):
        self.value = value
    def __repr__(self):
        return str(self.value)
    def __call__(self):
        return self.value
    def __add__(self, other):
        return Scalar(self.value + other.value)
    def __lt__(self, other):
        return self.value < other.value
    def ___le__(self, other):
        return self.value <= other.value
    def __eq__(self, other):
        return self.value == other.value
    def __ne__(self, other):
        return self.value != other.value
    def __gt__(self, other):
        return self.value > other.value
    def __ge__(self, other):
        return self.value >= other.value

可以像这样使用:

>>> s1 = Scalar(1.2)
>>> s2 = Scalar(2.1)
>>> s1 + s2
3.3
>>> s1 < s2
True
>>> s1 > s2
False
>>> s1 != s2
True
>>> s1 <= s2
True
>>> s1 >= s2
False

还有__int____float__魔术方法,您可以像这样实现和使用(这在语义上更正确):

>>> a = int(s)
>>> a = float(s)

答案 1 :(得分:1)

据我所知,a = s示例无法实现这一点。您必须更改赋值运算符=的行为。赋值运算符对右边的对象没有任何作用,只是复制对它的引用(至少在对象的情况下)。

通常,可以使用operator overloading更改自定义类的内置运算符的行为,但Python不会为赋值(=)提供此类选项,因为它与添加(+)和甚至平等(==)之类的运算符有多么不同。

相关问题