Refactor with pyCharm from “user” to “self.user”

2020-06-09 01:56发布

问题:

I want to move a variable from local scope to object level. The new code should use self.user and not user like before:

class Foo(object):
    def test_foo(self):
        user=User()
        ...
        user.do()

New code should look like:

class Foo(object):
    def test_foo(self):
        self.user=User() # I can remove this line by hand
        ...
        self.user.do()

I tried to refactor>>rename from user to self.user but pyCharm says: "Inserted identifier is not valid"

How can I refactor this with pyCharm?

回答1:

What you are trying to do is not a simple rename, but creating a new instance attribute. As such, instead of using Rename you should use Extract > Field menu item. Alternatively you can access this refactoring as Ctrl+Alt+F (this depends on the shortcuts you have chosen. Mine is the default for KDE).