简体   繁体   English

如何在我的 static 方法中调用运算符重载方法?

[英]How do I call an operator overload method inside my static method?

I'm slowly teaching myself Classes in Python and have hit a brick wall.我正在慢慢地自学Python中的课程并且已经碰壁了。 I could desperately use some help.我可以拼命地使用一些帮助。

I have created the base class, Number , and would like to figure out how to do two things:我已经创建了基础 class, Number ,并且想弄清楚如何做两件事:

  1. Overload the function of addition() of the class Number through the child class Rational(Number) , and update the object from which it is called Overload the function of addition() of the class Number through the child class Rational(Number) , and update the object from which it is called
  2. Create a static method addition that calls the overload function in its return statement and serves as a method override of its parent class创建一个 static 方法addition ,在其返回语句中调用重载 function 并用作其父 class 的方法覆盖

I've managed to write the following lines of code:我设法编写了以下代码行:

class Number:
    def __init__(self, number):
        self.number = number

    def addition(self, other_rational_num):
        pass

class Rational(Number):
    def __init__(self, p, q, number):
        super().__init__(number)
        self.__p = p
        self.__q = q

    def __add__(self, other_rational_num):
        number = self.number + other_rational_num.number
        return Number(number)

    @staticmethod
    def addition(number, other_rational_num):
        return Rational.__add__(number, other_rational_num)

If I type the basic operation in the static method's return statement return number + other_rational_num , I don't get an error.如果我在 static 方法的 return 语句return number + other_rational_num中键入基本操作,我不会收到错误。 But how can I leverage the overload method I already created?但是我怎样才能利用我已经创建的重载方法呢?

Any support is much appreciated!非常感谢任何支持!

Why is it a static method?为什么是 static 方法? Why not just:为什么不只是:

    def addition(self, other_rational_num):
        return self.__add__(other_rational_num)

And do you really want a Rational plus a Rational to return a Number?你真的想要一个 Rational 加上一个 Rational 来返回一个数字吗? That seems odd.这似乎很奇怪。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM