【发布时间】:2020-12-17 21:08:21
【问题描述】:
似乎在使用 PyCharm 时在函数中提取参数时唯一的选择是将所选对象添加为新参数的默认值。有时最好用所选对象替换所述函数的所有用法,例如在 IntelliJ 中,即来自与 Pycharm 相同创建者的 Java IDE。
我知道在 Java 中不允许使用默认值,但在 Python 中具有功能并不意味着它始终是最佳选择。在使用 Pycharm 时提取(或引入)参数时,可以选择以下选项之一:
- 通过添加新参数更改函数的签名并将所选对象添加为其默认值(实际行为)
- 通过添加新参数更改函数的签名并更改其所有用法以使用所选参数调用函数(行为不可用)
有没有办法像选项 2 那样提取参数?
例如,在一个测试类中,我可以在下面的函数中实例化目标类的对象
from unittest import TestCase
EMAIL ="a@b.com"
# Placeholder for object creation (a class' constructor, for example)
create_object = lambda email: "an object"
class Test(TestCase):
def test_1(self):
test_object = self.get_test_object()
# ...
def test_2(self):
test_object = self.get_test_object()
# ...
def test_3(self):
test_object = self.get_test_object()
# ...
def get_test_object(self):
# Use the EMAIL constant to create a test_object
test_object = create_object(EMAIL)
return test_object
现在假设我想将电子邮件作为参数添加到函数“get_test_object”,而不是使用全局变量“EMAIL”。在 Pycharm 中,我右键单击 EMAIL -> Refactor -> Introduce Parameter 并输入参数名称。这不会改变用法,只会设置一个具有默认值的新参数,如下所示
def get_test_object(self, email=EMAIL):
# Use the EMAIL constant to create a test_object
test_object = create_object(email)
return test_object
如果我想将该函数与另一封电子邮件一起使用,我可以通过调用“get_test_object('c@d.com')”来实现,但该函数的其他用法会强制读者隐式检查它是什么电子邮件使用。在这种情况下,我认为如果它更改所有用法而不是添加默认值会更好,因此在添加函数的新用法时,它会像这样:
from unittest import TestCase
EMAIL ="a@b.com"
# Placeholder for object creation (a class' constructor, for example)
create_object = lambda email: "an object"
class Test(TestCase):
def test_1(self):
test_object = self.get_test_object(EMAIL)
# ...
def test_2(self):
test_object = self.get_test_object(EMAIL)
# ...
def test_3(self):
test_object = self.get_test_object(EMAIL)
# ...
def test_4(self):
test_object = self.get_test_object("c@d.com")
# ...
def get_test_object(self, email):
test_object = create_object(email)
return test_object
【问题讨论】: