我是靠谱客的博主 懵懂菠萝,最近开发中收集的这篇文章主要介绍在python中定义类时、运算符重载,运算符重载python自定义类,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

say I want to overload an operator (lets say + for now) for some class I've created,

class A (object):

#code here

and then:

a = A()

b = A()

what would I do to define:

c = a + b

or something along those lines?

(note: this question is purely theoretical I will likely use this at some time, just not currently (unless its really easy and I really need a use for it))

(p.s. if it is possible to do this for other things such as and, or, not, str, e.t.c.)

解决方案

Since A is the first operand of the binary operator, you should define A.__add__(). If A was the second operand and there was no way to change the class of the first operand, you would have to define A.__radd__().

最后

以上就是懵懂菠萝为你收集整理的在python中定义类时、运算符重载,运算符重载python自定义类的全部内容,希望文章能够帮你解决在python中定义类时、运算符重载,运算符重载python自定义类所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(29)

评论列表共有 0 条评论

立即
投稿
返回
顶部