Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the introduction and usage of PyGetter And Setter in PyCharm plug-in development practice

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

In this issue, the editor will bring you the introduction and usage of PyGetter And Setter in the practice of PyCharm plug-in development. The article is rich in content and analyzes and narrates it from a professional point of view. I hope you can get something after reading this article.

Background demand

In object-oriented design, such as Java language, in order to control the modification entry of object properties, we often set the property to private, and then access and modify the property through getter and setter methods.

But in the Python language, there is no Java access control character, and the properties of the object can be accessed and modified directly.

For the sake of good design specification, we can stipulate that all object properties in the Python class should begin with an underscore "_" prefix, and write getter and setter methods for this property to prohibit direct references when referenced elsewhere.

In IDE such as IDEA, you can generate getter and setter methods directly from the object properties of Java, but there is no such functionality for Python. A large number of getter and setter methods are exhausting, so a plug-in is needed to help automate the generation of getter and setter methods for Python object properties.

Build an environment

To write a plug-in development environment for the IDEA series, you can see my previous article: "IntelliJ IDEA/Android Studio plug-in Development Guide"

Official development document: IntelliJ Platform SDK

Process disassembly

Example of Python file:

Class Test (object): def _ _ init__ (self): self._var1 = "" self._var2 = 0

After defining the requirements, input (python object attribute definition code), and output (PyCharm plug-in automatically generates getter and setter), we disassemble the process of this plug-in:

First, the user selects the text content of the corresponding line, and the plug-in gets the content text

Filter out variables in the content text, in this case, _ var1, _ var2

Getter and setter methods for assembling variables

Calculate the position to be inserted

Write back to the editor

1. Get text

In the PyCharm plug-in, the Editor object is the editor's overview, which contains many Model, such as

CaretModel caretModel=editor.getCaretModel (); / / used to describe the insertion cursor SelectionModel selectionModel = editor.getSelectionModel (); / / to describe the selected text FoldingModel foldingModel = editor.getFoldingModel (); / / to describe the code folding area IndentsModel indentModel = editor.getIndentsModel (); / / to describe indentation.

Here, all we need is SelectionModel.

/ / get the selected text object SelectionModel selectionModel = editor.getSelectionModel (); / / get the selected part of the string String selectedText = selectionModel.getSelectedText (); 2. Regular matching

After getting the selected text, it is possible to select multiple lines containing multiple variables, so we need to get a list of variables.

Observing that all the variables are self.abc=xxx patterns, we can consider using regular matching to get the abc from it.

The classes in Java responsible for regular matching and getting matching strings are Pattern and Matcher.

/ * get the value in all self.value in the selected text

* e.g. Self.value = xxx,or self._value = xxx

* you can get the value * * @ param selectedText selected text * @ return variable string list * / public ArrayList getFieldList (String selectedText) {ArrayList list = new ArrayList (); / / delete all spaces selectedText = selectedText.replaceAll ("", ") / / regular matching gets the variable string String reg = "self. (. *?) ="; Pattern pattern = Pattern.compile (reg); Matcher matcher = pattern.matcher (selectedText); while (matcher.find ()) {list.add (matcher.group (1));} return list;} 3. Assembling method

The getter and setter methods in Python are very simple, so we can create a template first:

/ / templates that define Getter and Setter String getterTemplate = "def get_word (self):\ n return self.field\ n"; String setterTemplate = "def set_word (self, word):\ n self.field = word\ n"

The reason why there are spaces is to match the indentation of PyCharm. The four spaces I use here are indented. If you use two spaces, you can change them here to two spaces.

You can't use\ t here. I tried\ t. If it can't be automatically converted to 4 spaces in PyCharm, an error will be reported.

For the variables obtained in the previous step, there may be no underline prefix or one or two underscore prefixes, such as var,_var,__var. Their corresponding gett and setter are as follows:

# if the variable is _ vardef get_var (self): return self._var;def set_var (self, var): self._var = var

You can see that variables need to be used in self.xxx, while the corresponding underscores need to be removed in the parameters of get_xxx and setter. So there are:

…… / / for variables of type "_ value", in the set method parameters, only "value" for (String field: fieldList) {String tmp = field; int i = 0; while (tmp.charAt (I) = ='_') {tmp = tmp.substring (1) is required } / / replace the variable String customGetter = getterTemplate.replaceAll ("word", tmp) .replaceAll ("field", field) in the template; String customSetter = setterTemplate.replaceAll ("word", tmp) .replaceAll ("field", field); stringBuilder.append ("\ n") .append (customGetter) .append ("\ n") .append (customSetter);}. 4. Calculation position

First of all, you need to get the Document object, which is responsible for describing the document, there are many methods responsible for the document, such as inserting strings in the file, calculating the number of lines of the file, calculating the length of the document, deleting the corresponding content, and so on.

Document document = editor.getDocument ()

For convenience and simplicity, we set getter and setter to be generated on the next line of the selected text.

/ / get the end position of the selected string int endOffset = selectionModel.getSelectionEnd (); / / get the position of the maximum insertion string (generated Getter and Setter function numeric strings) int maxOffset = document.getTextLength (); / / calculate the line number of the selected string, and get the starting offset of the first character of the next line by the line number int curLineNumber = document.getLineNumber (endOffset) Int docLineCount = document.getLineCount (); / / if the current number of file lines is not enough to support the next line of the selected text, that is, the selected text contains the last line, insert a blank line if (docLineCount-1)

< curLineNumber + 1) { Runnable runnable = () ->

Document.insertString (maxOffset, "\ n"); WriteCommandAction.runWriteCommandAction (project, runnable);} int nextLineStartOffset = document.getLineStartOffset (curLineNumber + 1); 5. Write back

Insert a string into a document. Instead of using document.insertString directly, it will error: Assertion failed: Write access is allowed inside write-action only (see com.intellij.openapi.application.Application.runWriteAction ()).

This task needs to be put into a Runnable and then dispatched by WriteCommandAction.

Reference: Write access is allowed inside write-action only

/ / A part of the code for manipulating a document needs to be put into runnable, otherwise IDEA will jam Runnable runnable = ()-> document.insertString (nextLineStartOffset, genGetterAndGetter (fieldList)); / / join the task, and the IDE will schedule the task WriteCommandAction.runWriteCommandAction (project, runnable); effect

At present, the effect is good. For the installation method and use method, see github's README.

Resources

Github link: https://github.com/mybichu/PyGetterAndSetter

These are the introduction and usage of PyGetter And Setter in the PyCharm plug-in development practice shared by the editor. If you happen to have similar doubts, you might as well refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report