【问题标题】:How to extract parameter in Pycharm without forcing a default value?如何在不强制使用默认值的情况下提取 Pycharm 中的参数?
【发布时间】:2020-12-17 21:08:21
【问题描述】:

似乎在使用 PyCharm 时在函数中提取参数时唯一的选择是将所选对象添加为新参数的默认值。有时最好用所选对象替换所述函数的所有用法,例如在 IntelliJ 中,即来自与 Pycharm 相同创建者的 Java IDE。

我知道在 Java 中不允许使用默认值,但在 Python 中具有功能并不意味着它始终是最佳选择。在使用 Pycharm 时提取(或引入)参数时,可以选择以下选项之一:

  1. 通过添加新参数更改函数的签名并将所选对象添加为其默认值(实际行为)
  2. 通过添加新参数更改函数的签名并更改其所有用法以使用所选参数调用函数(行为不可用)

有没有办法像选项 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

【问题讨论】:

    标签: python pycharm


    【解决方案1】:

    我发现这样做的唯一方法是分两步:

    1. 如上图,在EMAIL中右键->重构->引入参数,输入参数名称
    2. 在函数的“email”参数(不是值)右键->重构->更改签名->取消勾选“在签名中使用默认值”

    执行 1 然后 2 将提取参数并更改所有函数用法以将其包含在最初需要的调用中。然而,它太麻烦了。最好只用 1 步完成。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-08
      • 2014-10-13
      • 1970-01-01
      • 2015-06-08
      • 2018-02-02
      • 2012-07-13
      相关资源
      最近更新 更多