PyCharm Plugin - add method to class

I try append PyFunction to PyClass:

StringBuilder builder = new StringBuilder("def abc(self):\n");
builder.append("\treturn 'Foo'");
PyFunction func = gen.createFromText(LanguageLevel.forElement(psiClass), PyFunction.class, builder.toString());
psiClass.add(func);

but generated code looks like:

class Demo(object):
def abc(self):
     return 'Foo'

instead:

class Demo(object):
     def abc(self):
          return 'Foo'

1 comment

You need to add the function to the statement list of the class, not to the class directly.

Note that you can find out answers to all questions like that by yourself, by using the PSI Viewer to look at the structure of the PSI tree generated by the Python parser.

0

Please sign in to leave a comment.