【问题标题】:Extract method and insert call after original method call在原始方法调用之后提取方法并插入调用
【发布时间】:2021-12-06 09:30:33
【问题描述】:

我正在使用 PyCharm,我正在尝试进行一些重构,但不知道如何以快速可靠的方式做到这一点。

我有一个方法做太多事情,我想将一部分提取到另一个方法中。提取的方法不应该在它被提取的方法中调用,而应该在调用方法中。

当前状态

class User():
  def doStuff(self):
    calculateA()
    calculateB()
    calculateC()

def callerA():
  # do other things before
  obj.doStuff()

def callerAA:
  # do other things before
  obj.doStuff()

#... and many more methods calling doStuff method

通缉

class User():
  def doStuff(self):
    calculateA()

  def doOtherStuff(self):
    calculateB()
    calculateC()

def callerA():
  obj.doStuff()
  obj.doOtherStuff()

def callerAA:
  obj.doStuff()
  obj.doOtherStuff()

#... and many more methods calling doStuff method and doOtherStuff

# Now I'll be able to create this new method only doing a subset of the original method
def aNewMethod:
   obj.doStuff()


这可能与 PyCharm 有关吗?一直在玩重构,没有任何运气。我想提取到方法中是很容易的部分,但是方法调用最终会出现在错误的位置。如果在 Intellij 中可以的话,我也有许可证,所以我可以切换。

【问题讨论】:

  • 有一个快捷键 Cntrl+Alt+M 可以将选定部分提取为方法
  • @Kris 是的,但是方法调用将在 doStuff() 方法中结束,我需要在每次调用 doStuff() 之后进行
  • 也许您可以使用搜索并将obj.doStuff() 替换为obj.doStuff()\nobj.doOtherStuff()
  • @LouisSaglio 这是这个简单示例的好方法。实际上,有时调用是多行的,我无法让正则表达式正常工作。

标签: python intellij-idea pycharm


【解决方案1】:

没有这样的选择。欢迎您在 https://youtrack.jetbrains.com/issues/PY 提交功能请求 有关如何使用 YouTrack 的信息:https://intellij-support.jetbrains.com/hc/en-us/articles/207241135-How-to-follow-YouTrack-issues-and-receive-notifications

【讨论】:

    【解决方案2】:

    第 1 步:将两个新方法提取到您的 User 类中

    这个:

    class User():
      def doStuff(self):
        calculateA()
        calculateB()
        calculateC()
    

    变成:

    class User():
      def doStuff(self):
        newMethodA()
        newMethodB()
    
      def newMethodA(self):
        calculateA()
    
      def newMethodB(self):
        calculateB()
        calculateC()
    

    第 2 步:内联 doStuff 方法

    class User():
    
      def newMethodA(self):
        calculateA()
    
      def newMethodB(self):
        calculateB()
        calculateC()
    
    def callerA():
      newMethodA()
      newMethodB()
    
    def callerAA():
      newMethodA()
      newMethodB()
    
    

    第 3 步:重命名方法

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-30
      • 2023-04-08
      • 1970-01-01
      • 1970-01-01
      • 2019-02-08
      相关资源
      最近更新 更多