Python number-like class that remembers arithmetic operations?

前端 未结 5 594
甜味超标
甜味超标 2020-12-05 05:46

I\'m wondering if there exists a python module that would allow me to do something like this:

x = MagicNumber()
x.value = 3
y = 2 * (x + 2) ** 2 - 8
print y          


        
5条回答
  •  醉梦人生
    2020-12-05 06:18

    Isn't this called a function? This may sound like a simple answer, but I mean it sincerely.

    def y(x):
        return 2 * (x + 2) ** 2 - 8
    

    Aren't you thinking in the wrong direction with this one?

    To address the clarification:

    class MyParams():
        distance = 0.0
        speed = 0.0
        def __call__(self):
            return self.distance / self.speed
    
    p = MyParams()
    p.distance = 13.4            # These are properties
    p.speed = 3.14               # where __get__ returns MagicNumber instances
    time = p()  # 4.26
    p.speed = 2.28
    time = p()  # 5.88
    

    I guess I'm more in favor of this type of a solution, although I see the benefit in the sympy module. Preference, I guess.

提交回复
热议问题