|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
看了小甲鱼的课后题摄氏度转化华氏度问题有个疑问???
--------------------------------答案--------------------------------
class C2F(float):
def __new__(cls,arg=0.0):
return float.__new__(cls,arg * 1.8 + 32)
---------------------------------自己写的-------------------------
class C2F:
def __new__(cls,arg:float):
return arg * 1.8 + 32
这两个都可以实现转化温度,两者有啥区别???
新手不太明白,希望大侠们能点拨点拨
把程序稍微增加点内容。
- class C2F(float):
- def __new__(cls,arg=0.0):
- return float.__new__(cls,arg * 1.8 + 32)
- def __radd__(self, other):
- return other - self
- a = C2F(20)
- print(a, type(a))
- print(10 + a)
复制代码
- 68.0 <class '__main__.C2F'>
- -58.0
复制代码
- class C2F:
- def __new__(cls,arg:float):
- return arg * 1.8 + 32
- def __radd__(self, other):
- return other - self
- a = C2F(20)
- print(a, type(a))
- print(10 + a)
复制代码
- 68.0 <class 'float'>
- 78.0
复制代码
这回有差别了,第一个得到的是C2F类,整数没有和它的加法,所以用radd
第二个得到的是浮点数类,整数可以和它相加,就没有调用C2F的radd
|
|