小编Jer*_* Ma的帖子

在python中,如何使两个不同的类乘以右操作数(__rmul__方法)的优先级?

我试图让以下内容起作用,但没有成功:

我定义了自己的类型Unit(从内置类型继承float)来实现具有单位的数量的代数.它做的事情是这样的:

class Unit(float):
"""provide a simple unit converter for a given quantity"""

    def __new__(cls, unit, num=1.):
        return super(Unit, cls).__new__(cls, num)

    def __init__(self, unit, num=1.):
        """set up base unit"""
        self.unit = unit

    def __str__(self,):
        return '{:s} {:s}'.format(super(Unit, self).__str__(), self.unit)

    def __rmul__(self, other):
        print 'rmul: {:f}'.format(super(Unit, self).__rmul__(other))
        return Unit(self.unit, super(Unit, self).__rmul__(other))

    def to(self,target):
        fun_conv = _conv(self.unit, target)
        return  Unit(target, num=fun_conv(self))



c = 3e8 * Unit('m/s')   # this will 1) create a Unit instance with magnitude '1' and …
Run Code Online (Sandbox Code Playgroud)

python overriding numpy class operator-keyword

5
推荐指数
1
解决办法
1315
查看次数

标签 统计

class ×1

numpy ×1

operator-keyword ×1

overriding ×1

python ×1