python - we are achieving function overloading by writing same method with different type of argument
问题描述
class area:
def __init__(self):
self.rad = 0.0
self.side = 0
self.length = 0
self.breadth = 0
self.ar1 = 0.0
self.ar2 = 0
self.ar3 = 0
def cal(self,r=0.0,s = 0):
if(r!=None):
self.rad = r
self.ar1 = 3.14*self.rad*self.rad
print(self.ar1)
elif(s!=None):
self.side = s
self.ar2 = self.side*self.side
print(self.ar2)
obj = area()
obj.cal(7.0)
obj.cal(12)
we are achieving function overloading by writing same method with different type of argument but while calling control goes into if part instead of elif part.we want achieve area of circle with if part and area of square using elif but calling for both the argument goes into if part.
解决方案
我认为你的问题是那些r!=None
和s!=None
。至少这肯定是一个会破坏您的代码的问题。我不确定是不是你要问的那个。
这些参数的默认值为0.0
和0
。两者都不等于None
。
- 如果要检查它们是否非零,可以比较
r != 0
和s != 0
。- … 或者可能
r != 0.0
- ……或者也许
not math.isclose(r, 0)
。
- … 或者可能
- 如果你想检查它们是否真实——
None
零和零都不是真实的,但非零数字是真实的——只需检查r
自身。 - 如果要检查它们是否被排除在调用之外,则需要将函数定义中的默认值更改为
None
.- ......但是你应该检查
is not None
,不是!= None
。
- ......但是你应该检查
同时,如果您同时传递两者的值会发生什么?或者两者都不是?
此外,如果您希望人们不通过s
就通过r
,唯一的方法是作为关键字参数(除非通过查看函数定义以查看默认值r
是什么,然后显式传递)。
那么,也许这些应该是仅限关键字的参数?
把它们放在一起,这里是你想要的猜测:
def cal(self, *, r=None, s=None):
if r is not None:
raise TypeError('cal() needs either r or s')
elif r is not None and s is not None:
raise TypeError('cal() needs only one of r or s')
elif r is not None:
self.rad = r
self.ar1 = 3.14*self.rad*self.rad
print(self.ar1)
else:
self.side = s
self.ar2 = self.side*self.side
print(self.ar2)
现在:
>>> obj = area()
>>> obj.cal(7.0)
TypeError: cal() takes 1 positional argument but 2 were given
>>> obj.cal()
TypeError: cal() needs either r or s
>>> obj.cal(r=7.0)
153.86
>>> obj.cal(s=12)
144
但实际上,有一种更简单的方法可以完成所有这些操作:
def circle(self, r):
# do circle stuff
def square(self, s):
# do square stuff
更容易编写,更容易阅读——无论是在定义端还是在调用端:
>>> obj.circle(7)
153.86
>>> obj.square(12)
144
推荐阅读
- machine-learning - 如何识别英文字母和非英文字母?
- c++ - 将文件读入数组并输出数组 C++
- python - conda 命令在 Mac OS X 10.5.3 下不起作用
- python - Python 线程,停止/启动/终止
- compiler-errors - 如何解决“找不到类型或命名空间名称'Didstopia'(您是否缺少 using 指令或程序集引用?)”
- r - 重复 id 时在行中绑定数据框
- python - 可以创建一个“with”块来运行它只包含一次的代码吗?
- javascript - Javascript切片数组查找最大值
- ios - 如何在仅从远程 CloudKit 数据库收到更改时收到通知?
- c++ - 如果需要数据包标头,通过 UDP 发送大型连续缓冲区的最有效方法是什么?