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 are the abbreviations that Python programmers should know

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

Share

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

This article mainly explains "what are the acronyms that Python programmers should know". The explanation in the article is simple and clear and easy to learn and understand. please follow the editor's train of thought to study and learn "what acronyms Python programmers should know".

1. OOP (object oriented programming)

The first acronym to be introduced is OOP-- object-oriented programming, which is the design on which Python is based.

Everyone knows that programming itself is about coding, but the program itself should be about data. The program needs to obtain input data, process data and output data. Note that the data discussed here is data in the most general sense and can include the number of tables, strings, user actions (such as clicking a button), images, and any form of data with information. The job of the code is to process all forms of data and render them in the way you want.

To get the job done, people need code that can process this data, and a common design pattern in modern programming languages, including Python, is to adopt the OOP paradigm. The idea is straightforward-we wrap the data with specific objects.

More specifically, objects can hold data (such as properties) and manipulate data (such as methods). For example, if we develop a racing game, we can build car objects, and each object can have specific properties, such as color, maximum speed, and weight. In addition, these objects can also perform operations such as braking and acceleration. The logical organization of these data is centered on the object (car).

Let's take a look at a specific example in Python. You can use the built-in str class to wrap string data, and people can not only use string objects to pass string data, but also change the way strings are represented. Take a look at a very trivial example.

> > # Create avariable of str type... Hello = "HelloPython!"... # Send the data toa function call... Print (hello)... # Manipulate thestring data with string methods... Hello_lower = hello.lower ()... Hello_upper = hello.upper ()... Print (lowercased:, hello_lower)... Print (uppercased:, hello_upper)... HelloPython! Lowercased: hello python! Uppercased: HELLOPYTHON!

String data processing

2.DRY (don't repeat yourself)

The principle of DRY (don't repeat yourself) is one of the most basic rules that every programmer should practice. The meaning is simple: if any duplicates are found in the code, it indicates that some refactoring is needed to minimize duplicated code or, if possible, to completely remove any duplicated signals.

The following example shows some code refactoring by applying the principle of DRY:

Defdo_something (item): pass # Repetativework do_something (item0) do_something (item1) do_something (item2) # Apply DRY for item in (item0, item1,item3): do_something (item)

Don't repeat yourself.

Another possibility of code refactoring is to find yourself dealing with a pile of data with the same structure. Instead of using a series of dictionaries, lists, or tuples to store everyone's data, you should consider using your own classes to process this data. This not only makes the programmer's code less prone to errors, but also helps the long-term maintainability of the code.

3. PIP (Python package installation and management tool)

The most important factor in Python's popularity is its open source nature, which brings a large number of free Python packages. According to Wikipedia, more than 235000 packages are indexed in the Python package Index (PyPI).

We can use the pip tool to install any package from PyPI. The installation process is very easy, as long as you use a single line of code in the command or terminal. The following code snippet summarizes some common uses. To learn more about the use of the pip tool, visit its official website: https://pip.pypa.io/en/stable/user_guide/.

# install latest version pip install package_name # install aparticular version pip install package_name==version_number # to uninstall apackage pip uninstall package_name # to show installedpackages pip list # to show theinformation about aparticular package pip show package_name # to install alist of dependencies, such as to clone a virtual environment pip install-rrequirements.txt

Example of using PIP

4. LEGB (function internal scope, function internal and embedded functions, global scope and built-in scope)

The LEGB rule refers to the order in which variables are found in Python, as shown in the following figure. Specifically, when the interpreter tries to parse variables, Python has four layers of scope-- knowing which values to bind to variables.

Start with the internal scope, which can be a function or class. If the interpreter finds the appropriate bound value for the variable, it stops looking for and uses the variable with that specific value.

Variable resolution rule

Otherwise, it will look at a higher level-- within the function and between the embedded functions. This range exists only in the nested structure of the function. When we declare a function in another function, we call the internal function the internal function and the external function the external function. When the interpreter tries to parse variables used within the scope of the internal function, if it cannot be parsed within the local scope, it will enter the closed scope, that is, the local scope of the external function.

If you still cannot resolve a variable in a closed scope, it goes to the global scope. The global scope is usually at the module level, usually a separate Python file. It is worth noting that when the package is imported into the current file, the functions and classes in the import will also become part of the global scope. The built-in scope is the functions, classes, and other modules to load when you start the interpreter so that these most basic objects are always available (such as print and other built-in functions).

5. MRO (method parsing order)

The method parsing order represents how methods or properties are typically parsed by Python or programming languages. Unlike the LEGB rules discussed above, which focus on solving variables, MRO focuses on objects and their method calls or how to get specific properties.

MRO is mainly discussed in the context of multiple inheritance-- classes that inherit from multiple classes (that is, superclasses) and / or inherit multiple layers of classes (that is, subclasses). Because both subclasses and superclasses share common methods that may have different implementations, the Python interpreter needs a mechanism to determine which method or property should be used in a particular call, which is what MRO is responsible for.

ClassX:... Defbin (self):... Print (f "bin called in X"). ClassY (X):... Defgo (self):... Print (f "go called Y"). ClassZ (X):... Defgo (self):... Print (f "go called Z"). ClassW (Y, Z):... Defbin (self):... Super (). Bin ()... Print (f "bin called W"). Defbingo (self):... Self.bin ()... Self.go (). W = W (). W.bingo ()... Bin called inX bin called W go called Y

Method parsing order

For an instance of class W (line 22), when we call the bingo () method, this method parses in its own class because it is defined in the class (lines 18-20). However, this method further calls the bin () and go () methods.

In a similar manner, the bin () method is resolved in its own class, but it calls the superclass's bin () method, as shown in line 15. But in its direct superclass (that is, Y and Z), the bin () method is not implemented, so Python is one level higher than the superclass of the superclass (such as X), where the bin () method is implemented and called.

It is worth noting that for W's go () method, both of its superclasses implement this method, but as you can see, this only calls the implementation used in the Y class. Because when the W class is defined, the inheritance order is Y and Z, which causes MRO to follow the same order.

Related to this, you can use the special method _ _ mro__ to find the MRO of a particular class. In addition, to demonstrate the importance of the class inheritance order, we created another class, where Class Z comes before Class Y, which changes the MRO of the W_ class.

> print (W Class MRO:, W.roommate _). ClassW_ (Z, Y):... Pass...... Print (W _ Class MRO:, Wend.roommrology _). WClassMRO: W_ClassMRO: (,)

Special method _ _ mro__

6. EAFP (it is easier to ask for forgiveness than permission) and LBYL (check in advance)

EAFP (it's easier to ask for forgiveness than permission) the coding style is the basis for Python's survival. Because Python is a dynamic programming language, it is possible to implement and modify existing instance objects, classes and even modules at run time. Therefore, it is recommended that you write code on the assumption that specific properties or functions are available.

In other words, if there may be specific problems with some code, bring them to the surface and solve them accordingly. By applying EAFP rules, if we want to go further, we can simply use try. The except statement writes specific code to handle potential exceptions that the code may throw. In short, the aim is to deal with accidents afterwards.

Contrary to the EAFP principle, there is another coding style called LBYL, which stands for "pre-check". Using this coding method, programmers can rule out all possible bad situations before running some code. As a result, you can see more if statements in more projects that follow LBYL principles. This coding style is to try to prevent all problems in a specific way.

The following code snippet shows possible scenarios for using EAFP and LBYL. Using the EAFP coding style, you just need to wrap the code and expected possible exceptions in try. Except statement, using the LBYL encoding style at the same time, you must use introspection and value checking to verify the conditions that apply before division.

As you can see, the EAFP code looks cleaner and does not create a nested structure. Of course, you can also apply LBYL to your project if you like, and eventually the project will still work in a similar way.

Defwith_EAFP_divide_ten_by (number): try: print (f 10 divided by {number} is {10 / number}. ) ExceptZeroDivisionError: print ("You can tdivide zero.") ExceptTypeError: print ("You canonly divide a number.") Defwith_LBYL_divide_ten_by (number): ifisinstance (number, int) orisinstance (number, float): if number = 0: print ("You can tdivide zero.") Else: print (f 10 divided by {number} is {10 / number}. ) Else: print ("You canonly divide a number.")

EAFP vs. LBYL

8. PEP (Python Enhancement proposal)

Coding styles were generally discussed in the previous section, but one of the most influential Python coding style guidelines is PEP 8--Python Enhancement recommendation # 8, written by BDFL (discussed below) and several other Python core maintainers.

PEP covers a lot of content-all Python-related content, and the entire list can be found on the official website (https://www.python.org/dev/peps/. Here are some famous articles:

PEP 8: Style Guide for Python Code

PEP 257: Docstring Conventions

PEP 20: The Zen of Python

PEP 498: Literal String Interpolation

PEP 202: List Comprehensions

PEP 405: Python Virtual Environment

9. BDFL (benevolent dictator)

What is BDFL? Here's the Wikipedia definition: benevolent BDFL is the title of a handful of open source software development leaders, who are usually project founders who retain the final say in disputes or disputes in the community.

Although this definition usually applies to open source software development, it was originally used in the Python community as a way to refer to Guido van Rossum (GvR), the creator of the Python programming language. He leaves office in 2018 after more than 20 years in the role of BDFL. You can find more stories about BDFL on Wikipedia.

10. REPL ("read-evaluate-output" loop)

In my opinion, REPL (read-evaluate-output cycle) is a convenient tool to make learning Python so easy. We can simply start learning Python coding as we do with commands or terminal windows, and we can use the pip tool to install the package as shown earlier. More importantly, you can write the first line of Python code immediately without writing any IDE tools that other programming languages might need (for example, it might be this line of code: print ("Hello World!")).

Let's take a quick look at it:

> print ("HelloWorld!") HelloWorld! > 3 > 26 > type (5)

REPL example

The REPL workflow is simple-read the code, evaluate it, print all applicable results in the evaluation in the console, and then cycle through these three steps to explore the various functions of Python. REPL is implemented as the default pattern in standard Python or other common Python development tools such as ipython, which is the basis of the famous Python learning and coding tool, Jupiter Notebook.

Python is a flexible and powerful OOP language created by BDFL GvR. With PIP, we can easily manage Python software packages and learn languages and various software packages in the console through REPL. When coding with Python, we want to follow the style outlined in PEP 8. Other important coding principles include DRY and EAFP. You can also do some LBYL in your coding if you like. LEGB rules and MRO will help you understand how to parse variables, properties, and functions to make your code work as expected.

Thank you for your reading, the above is the content of "Python programmers should know what acronyms have". After the study of this article, I believe you have a deeper understanding of the acronyms that Python programmers should know. The specific use of acronyms also needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

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