繁体   English   中英

将参数 self 传递给函数

[英]Passing arguments self into function

如何将参数 ( a , b , c ) 传递给二次公式的函数,而不必在函数中重新定义它们? 我知道我可以在公式中使用self.a而不仅仅是a (对于bc )但是我如何将参数self.a作为aself.b作为bself.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)

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

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)

你不必重新定义任何东西。 __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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM