Rules of thumb for when to use operator overloading in python

后端 未结 4 760
走了就别回头了
走了就别回头了 2020-12-03 11:15

From what I remember from my C++ class, the professor said that operator overloading is cool, but since it takes relatively a lot of thought and code to cover all end-cases

4条回答
  •  无人及你
    2020-12-03 11:49

    Python's overloading is "safer" in general than C++'s -- for example, the assignment operator can't be overloaded, and += has a sensible default implementation.

    In some ways, though, overloading in Python is still as "broken" as in C++. Programmers should restrain the desire to "re-use" an operator for unrelated purposes, such as C++ re-using the bitshifts to perform string formatting and parsing. Don't overload an operator with different semantics from your implementation just to get prettier syntax.

    Modern Python style strongly discourages "rogue" overloading, but many aspects of the language and standard library retain poorly-named operators for backwards compatibility. For example:

    • %: modulus and string formatting
    • +: addition and sequence concatenation
    • *: multiplication and sequence repetition

    So, rule of thumb? If your operator implementation will surprise people, don't do it.

提交回复
热议问题