Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refactor class method to property using Pycharm

I have the following class:

class Dogs(object):
    def __init__(self):
        self.names = []
        self.breeds = set()

    def number(self):
        return len(self.names)

I want to change number to being a property. This means I also want to change all of it usages. Does PyCharm have this built into it's refactoring tools? It seems to be according to this issue.

At this point, I'm doing "find all usages" and then manually fixing each instance. If there isn't a specific refactoring tool for changing a method to a property, is there some way to use "find all usages" more effectively?

like image 257
Seanny123 Avatar asked Apr 19 '17 04:04

Seanny123


People also ask

How do you make a property method?

Press Ctrl+Shift+R and then choose Convert Method to Property.

What is refactor in Python?

Refactoring means organizing your code without modifying its original functionality. Refactoring is the process of making small changes or adjustments to your code without affecting or changing how the code functions while in use.

How do you create a function in Pycharm?

From the main menu or from the context menu, select Refactor | Extract | Method or press Ctrl+Alt+M . In the Extract Method dialog that opens, specify the name of the new function.


1 Answers

Yes, you can refactor a method to a property in PyCharm. Strangely, this does not correspond to any entry in the "Refactor" menu.

Just place the editor cursor on the name of the method and press Alt+ shortcut to show the available Intentions.

Then, select "Convert method to property".

"Convert method to property" intention

You can also trigger the global action search with Ctrl+Shift+A and select the intention from there.

Alternative

like image 54
pietrodn Avatar answered Oct 07 '22 22:10

pietrodn