python如何实现自定义类和不同类型数据相乘

回答:

基本方法__add__(self,other)   然后使用   isinstance判断

但此方法默认other是在右边相乘,故可以实现(userclass*10)的操作

但不能实现(10*userclass)的操作

因此需要使用__radd__(self,other)方法

此时的other 是做运算符(“+”号)左边的那个类,然后isintance(other,int)一下,就能和数字相乘了

class operator:
    def __add__(self, other):
        if isinstance(other, int):
            return self.value+other
        else:
            return self.value+other.value
    def __radd__(self, other):
        if isinstance(other, int):
            return self.value+other
        else:
            return self.value+other.value
class OPEN(operator):

    def __init__(self, pdframe):
        self.value = pdframe['open'].tolist()[DAY]
if __name__ == '__main__':    
    open = OPEN(pd_data)
    close = CLOSE(pd_data)
    print(6+open)

解决历程:

百度搜索不论怎么搜都是千篇一律,没有解决问题ㄟ( ▔, ▔ )ㄏ

只好求助于newbing了

 

 简直verygood

猜你喜欢

转载自blog.csdn.net/weixin_52013159/article/details/130001866