首页 > 解决方案 > 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.

标签: python

解决方案


我认为你的问题是那些r!=Nones!=None。至少这肯定是一个会破坏您的代码的问题。我不确定是不是你要问的那个。

这些参数的默认值为0.00。两者都不等于None

  • 如果要检查它们是否非零,可以比较r != 0s != 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

推荐阅读