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

2024-05-14 16:22:56 发布

您现在位置: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) 

但是当我运行这个程序时,我得到了一个错误:

^{pr2}$

我是python新手,如果我在这里遗漏了一些东西,我很抱歉,但是据我所知,我在调用函数时只传递了两个参数:self.near(az, -2.5003175907168385)

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


Tags: 代码self参数def单元测试unittesttestcaseclass
3条回答

任何类方法中的第一个变量都是对类实例的引用。您的方法需要两个变量:val1val2,但是当您调用self.near(val1, val2)时,它相当于调用一个以selfval1和{}作为参数的函数。在

Python Docs on Classes,第二段:

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

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

另外,我建议将保证金作为一个变量传递,而不是将其作为一个全局变量(我目前认为是这样)。在

相关问题 更多 >

    热门问题