Extract field
The Extract Field refactoring lets you declare a new field and initialize it with the selected expression. The original expression is replaced with the usage of the field.
Extract a field in place
Place the caret within a piece of code you want to extract into a field.
Press Ctrl+Alt+F or go to
in the main menu.Select an expression you want to introduce as a field.
If PyCharm detects more than one occurrence in your code, it lets you specify which occurrences to replace.
If relevant, specify where the new field will be initialized - in the current method, or in a class constructor.
Specify the name of the field. Select the name from the list or type the name in the box with a red border.
To complete the refactoring, press Tab or Enter.
Example
import math
class SolverEquation:
def demo(self):
a = 3
b = 25
c = 46
root1 = (-b + math.sqrt(b**2 - 4*a*c)) / (2*a)
root2 = (-b - math.sqrt(b**2 - 4*a*c)) / (2*a)
print(root1, root2)
import math
class SolverEquation:
def demo(self):
a = 3
b = 25
c = 46
self.math_sqrt = math.sqrt(b ** 2 - 4 * a * c)
root1 = (-b + self.math_sqrt) / (2 * a)
root2 = (-b - self.math_sqrt) / (2 * a)
print(root1, root2)
Last modified: 08 October 2024