python中__add__方法_如何为Python类创建add方法?

class FootMeasure(object):

def __init__(self, feet=0, inches=0):

"""Initiates feet and inches to 0. User can enter custom numbers"""

self.__feet = feet

self.__inches = inches

def __repr__(self):

"""Returns inches higher than 11 to a foot representation

Returns 60 inches at 5 ft instead of 5 ft 0 inches

Returns 0 as 0 ft 0 inches

"""

if self.__inches == 0:

return str(self.__feet) + ' ft '

elif self.__inches > 11:

feet = int(self.__inches / 12)

remainder = self.__inches % 12

return str(feet) + ' ft ' + str(remainder) + ' in '

else:

return str(self.__feet) + ' ft. ' + str(self.__inches) + ' in. '

def __add__(self):

"""Returns two FootMeasures added together"""

我是新来上课的,所以我有点困惑怎么做。我知道这可能是一个简单的过程,但我只是找到了一些关于分数相加的例子,我搞不懂。那么,我该如何为它创建一个add方法呢?例如,如果我说first=FootMeasure(1,1),second=FootMeasure(1,1)。结果=第一次+第二次。我当然想要2英尺的成绩。我怎么能这么做?在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值