【问题标题】:Python - How do i perform operations on my own class in both directions?Python - 我如何在我自己的类上双向执行操作?
【发布时间】:2020-06-19 19:48:45
【问题描述】:

例如,让我的 class= 对象

当我做print(object * int) 时一切顺利

但是,当我执行 print(int * object) 时。我收到一个错误,其中我的类对象无法添加到 int 对象,这是一个可以在不更改默认数据类型的情况下解决的问题吗?

【问题讨论】:

    标签: python python-3.x class oop error-handling


    【解决方案1】:

    如果覆盖 __mul__,则可以调用 print(object*int)。

    如果你重写 __rmul__,你可以调用 print(int*object)。

    写a*b时,优先调用a.__mul__(b),如果没有实现,则调用b.__rmul__(a)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      • 2011-02-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多