PyCharm 2.7.2 Web Help

When the Extract Method refactoring is invoked, PyCharm analyses the selected block of code and detects variables that are the input for the selected code fragment and the variables that are output for it.

BeforeAfter
import math

class Solver:
def demo(self):
    a = 3
    b = 25
    c = 46
    root1 = (-b + math.return_type_of_sqrt(b**2 - 4*a*c)) / (2*a)
    root2 = (-b - math.return_type_of_sqrt(b**2 - 4*a*c)) / (2*a)
    print(root1, root2)

Solver().demo()
                
import math

class Solver:
def eval_roots(self, a, b, c):
    d = b**2 - 4*a*c
    root1 = (-b + math.sqrt(d)) / (2*a)
    root2 = (-b - math.sqrt(d)) / (2*a)
    return root1, root2

def demo(self):
    a = 3
    b = 25
    c = 52
    root1, root2 = self.eval_roots(a, b, c)
    print(root1, root2)
        
Solver().demo()
                
py_extract_substring1py_extract_substring_method
To extract a method
  1. In the editor, select a block of code to be transformed into a method or a function.

    Tip

    The code fragment to form the method does not necessarily have to be a set of statements. It may also be an expression used somewhere in the code.

  2. On the main menu or on the context menu of the selection, choose Refactor | Extract | Method or press Ctrl+Alt+MCtrl+Alt+M.
  3. In the Extract Method dialog box that opens, specify the name of the new method.
  4. To create a static method, select the Declare Static check box.
  5. In the Parameters area, do the following:
    • Specify the variables to be passed as method parameters, by selecting/clearing the corresponding check boxes; if a parameter is disabled, a local variable of the corresponding type, with the initial value ... will be created in the extracted method, so that you will have to enter the initializer with an appropriate value manually.
    • Rename the desired parameters, by double-clicking the corresponding parameter lines and entering new names.
  6. In the Parameters area, do the following:
    • Specify the variables to be passed as method parameters by selecting/clearing the corresponding check boxes.
    • Rename the desired parameters, by double-clicking the corresponding parameter lines and entering new names.
  7. In the Visibility area define the method's visibility scope.
  8. Check the result in the Signature Preview pane and click OK to create the method. The selected code fragment will be replaced with a method call. Additionally, PyCharm will propose to replace any similar code fragments found within the current class.
  9. Check the result in the Signature Preview pane and click OK to create the method. The selected code fragment will be replaced with a method call.

See Also

Reference:

Web Resources: