简体   繁体   English

Python说我向我的函数传递了太多参数?

[英]Python saying I'm passing in too many parameters to my function?

I have some python code that contains unit tests like below: 我有一些python代码包含如下所示的单元测试:

class SunCalcTestCases(unittest.TestCase):
    """Tests for `suncalc.py`."""
    def near(val1, val2):
        return abs(val1 - val2) < (margin or 1E-15)

    def test_getPositions(self):
        """Get sun positions correctly"""
        sunPos = suncalc.getPosition(self.date, self.lat, self.lng)
        az = sunPos["azimuth"]
        res = self.near(az, -2.5003175907168385) 

But when I run this I get the error: 但是当我运行这个时,我得到错误:

Traceback (most recent call last):
  File "test.py", line 64, in test_getPositions
    res = self.near(az, -2.5003175907168385)
TypeError: near() takes exactly 2 arguments (3 given)

I am new to python so I apologize if I am missing something here, but as far as I can tell I am only passing in two parameters when I call the function: self.near(az, -2.5003175907168385) 我是python的新手,所以我很抱歉,如果我在这里遗漏了一些东西,但据我所知,我在调用函数时只传递了两个参数: self.near(az, -2.5003175907168385)

Can anyone tell me why it thinks I'm passing in 3 parameters? 谁能告诉我为什么它认为我传递了3个参数?

The first variable in any class method is a reference to the class instance. 任何类方法中的第一个变量是对类实例的引用。 Your method is expecting two variables: val1 and val2 , but when you call self.near(val1, val2) it is the equivalent of calling a function with self , val1 , and val2 as the arguments. 你的方法需要两个变量: val1val2 ,但是当你调用self.near(val1, val2)它相当于调用一个带有selfval1val2作为参数的函数。

From Python Docs on Classes , second paragraph: 来自Python Docs on Classes ,第二段:

the method function is declared with an explicit first argument representing the object, which is provided implicitly by the call 方法函数使用表示对象的显式第一个参数声明,该参数由调用隐式提供

It has been mentioned before but my answer would be "your method near should be static". 之前已经提到过,但我的答案是“你的方法应该是静态的”。 Rather than passing self, I would make the method static using the @staticmethod decorator. 我不是传递self,而是使用@staticmethod装饰器使方法静态化。 This is given the fact that passing self has no benefits. 这是因为传递自我没有任何好处。 Even more, if you pass self as an argument, a quality checker like Sonar Python Lint combination will flag it as "it should be static". 更重要的是,如果你将self作为参数传递,像Sonar Python Lint组合这样的质量检查器会将其标记为“它应该是静态的”。 This is something I often forget about it ( Module function vs staticmethod vs classmethod vs no decorators: Which idiom is more pythonic? ). 这是我经常忘记的事情( 模块函数vs staticmethod vs classmethod vs no decorators:哪个成语更pythonic? )。

Also, I would recommend passing margin as a variable as well rather than making it a global variable which I imagine it is at the moment. 另外,我建议将margin作为变量传递,而不是将它作为一个全局变量,我想这是目前的变量。

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

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