透明地为自定义数字类型赋值

2024-04-19 01:10:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建一个自定义的数字类型。基本上是一个float,它的值在赋值之后由我的自定义类处理。 我有seen examples解释了如何创建类并将其作为公共类型(int/float/…)读取。 然而,关于如何使值赋值像浮点变量那样透明,还没有一个例子。你知道吗

到目前为止,我看到的是:

a = MyCustomFloat( 20. )
print(a) # prints "20"

我要找的是:

a = MyCustomFloat()
a = 20. # assign new value ; "a" is still an instance of MyCustomFloat
print(a) # prints "20"

这有可能吗?你知道吗

如果是,怎么做?你知道吗


Tags: 类型newvalue数字floatprintsexamples例子
2条回答

不可能在变量级别重写此行为,但如果您愿意将a定义为类的属性,则可以实现using descriptors。你知道吗

class MyCustomClass:
    def __init__(self, val):
        self.val = val

    def __get__(self, instance, kls=None):
        return self 

    def __repr__(self):
        return repr(self.val)

    def __set__(self, instance, val):
        if not isinstance(val, (int, float)):
            raise TypeError('Only objects of type int and float can be assigned')
        self.val = val  # This can be self.val = MyCustomClass(val) as well.


class NameSpace:
    a = MyCustomClass(20.)

演示:

>>> namespace = NameSpace()

>>> namespace.a
20.0

>>> type(namespace.a)
<class '__main__.MyCustomClass'>

>>> namespace.a = 12

>>> type(namespace.a)
<class '__main__.MyCustomClass'>

>>> namespace.a
12

>>> namespace.a = '1234'
                                     -
TypeError                                 Traceback (most recent call last)
<ipython-input-40-6aced1b81d6b> in <module>()
  > 1 namespace.a = '1234'
...
TypeError: Only objects of type int and float can be assigned

在变量级别,惟一的选择是使用mypy进行一些静态检查(正如Chris所提到的)。这不会阻止在运行时进行此类分配,但可以在部署代码之前运行静态代码分析器时指出此类分配。你知道吗

由于Python是一种动态语言,您可以为以后的语言分配任何需要的内容,因此预先声明其类型可能对您没有任何好处,因为您可以执行以下操作:

a = MyType()
a = 'hi'
a = 2.3

也就是说,如果你做了

a = MyType()
a = 20.
type(a) 

它可能会返回默认值(float或float64)。如果您想要静态类型(一旦您声明aMyType类型,它将保持这种方式),我建议使用mypy

希望有帮助

相关问题 更多 >