我有一些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个参数吗?在
任何类方法中的第一个变量都是对类实例的引用。您的方法需要两个变量:}作为参数的函数。在
val1
和val2
,但是当您调用self.near(val1, val2)
时,它相当于调用一个以self
、val1
和{从Python Docs on Classes,第二段:
您忘记在
near
函数中传递self
def near(self, val1, val2):
Meaning of @classmethod and @staticmethod for beginner?
What is the difference between @staticmethod and @classmethod in Python?
之前已经提到过,但我的回答是“你的方法应该是静态的”。 我不想传递self,而是使用@staticmethod decorator使方法成为静态的。这是因为“自我超越”没有任何好处。更重要的是,如果您将self作为参数传递,像Sonar Python Lint组合这样的质量检查器会将其标记为“它应该是静态的”。这是我经常忘记的事情(Module function vs staticmethod vs classmethod vs no decorators: Which idiom is more pythonic?)。在
另外,我建议将保证金作为一个变量传递,而不是将其作为一个全局变量(我目前认为是这样)。在
相关问题 更多 >
编程相关推荐