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

I have some python code that contains unit tests like below:

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)

Can anyone tell me why it thinks I'm passing in 3 parameters?


You forgot to pass self in near function

def near(self, val1, val2):

Meaning of @classmethod and @staticmethod for beginner?

What is the difference between @staticmethod and @classmethod in Python?


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.

From Python Docs on Classes, second paragraph:

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. 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". This is something I often forget about it (Module function vs staticmethod vs classmethod vs no decorators: Which idiom is more 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.

链接地址: http://www.djcxy.com/p/54280.html

上一篇: 创建一个Python类方法

下一篇: Python说我传递了太多的参数给我的函数?