2015-07-21 121 views
2

我有一个包含类似下面的单元测试的一些Python代码: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) 

但是当我运行此我得到的错误:

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) 

我是新来的Python,所以我很抱歉,如果我的思念这里的东西,但据我可以告诉我,当我调用该函数时,只传递两个参数:self.near(az, -2.5003175907168385)

有谁能告诉我为什么它认为我传递3个参数吗?

+3

'def near(self,val1,val2):' – LittleQ

回答

5
+0

噢 - 这可能是一个愚蠢的问题,但为什么我必须在自己的函数中传入'self',如果我没有引用它呢? –

+3

@AbeMiessler [参考](http://stackoverflow.com/questions/2709821/what-is-the-purpose-of-self-in-python) –

+0

python类对象有三种方法。 @AbeMiessler https://docs.python.org/2/faq/design.html#why-must-self-be-used-explicitly-in-method-definitions-and-calls – LittleQ

1

在任何类方法中的第一变量是对类实例的引用。您的方法预计有两个变量:val1val2,但是当您调用self.near(val1, val2)时,它等效于调用self,val1val2作为参数的函数。

Python Docs on Classes,第二段:

the method function is declared with an explicit first argument representing the object, which is provided implicitly by the call

1

它之前已经提及,但我的回答是“你的方法附近应该是静态的。” 而不是传递自己,我会使用@staticmethod装饰器使方法静态。这是因为通过自我没有好处。更重要的是,如果您将自己作为参数传递,像Sonar Python Lint组合这样的质量检查器会将其标记为“它应该是静态的”。这是我经常忘记的事情(Module function vs staticmethod vs classmethod vs no decorators: Which idiom is more pythonic?)。

此外,我会建议将margin作为变量来使用,而不是将它作为我想象的全局变量。

相关问题