0

如何将参数 ( a, b, c) 传递给二次公式的函数,而不必在函数中重新定义它们?我知道我可以使用self.a而不是只在公式内部使用(和a相同)但是我如何将参数as 、as和传递给函数?bcself.aaself.bbself.c

class Calc:

    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c
    
    def quadraticformula(self):
        c = self.c
        b = self.b 
        a = self.a
        
        neg = ((b*-1)-(sqrt((b**2)-4*a*c)))/(2*a)
        pos = ((b*-1)+(sqrt((b**2)-(4*a*c))))/(2*a)
        return (pos,neg)
4

2 回答 2

2

与其使用带有构造函数的类,不如使用一般的普通函数

def calc(a, b, c):
    neg = ((b*-1)-(sqrt(b**2 - 4*a*c)))/(2*a)
    pos = ((b*-1)+(sqrt(b**2 - 4*a*c)))/(2*a)
    return pos, neg

然后调用函数:

>>> calc(1, 2, -3)
(1.0, -3.0)
于 2020-08-30T17:29:30.633 回答
0

你不必重新定义任何东西。该__init__方法允许该类的所有其他方法能够访问该变量。因此,一旦您在方法中实际定义了传递给的变量(您将其作为函数引用,但它不是),__init__您所要做的只是用您需要的任何操作来引用它。

# within you quadraticformula method
...
neg = ((self.b*-1)-(sqrt(self.b**2 - 4*self.a*self.c)))/(2*self.a)
pos = ((self.b*-1)+(sqrt(self.b**2 - 4*self.a*self.c)))/(2*self.a)
return pos, neg

将属性传递给类时,您已经创建了一个实例,如下所示:

a = # something
b = # something
c = # something

cl = Calc(a, b, c)
cl.quadraticformula() # call the method (a function with a method) of the function here

# You can call this method in the __init__ method if you want to 
# execute as soon as you call the class instead of using the instance 
# to reference it
class Calc:
  def __init__(self,a,b,c):
     self.a = a
     self.b = b
     self.c = c
     self.quadraticformula
于 2020-08-30T17:25:38.917 回答