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 skills of Python abbreviation

2025-02-24 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 skills of Python abbreviation". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Next, let the editor take you to learn what are the skills of Python abbreviations.

1. OOP (object oriented programming)

The first acronym we must know is OOP-- object-oriented programming, which is the basis of Python programming. We know that programming itself is about coding, but the program itself should be about data. Our program needs to obtain input data, process data and output data. Note that the data discussed here is data in a general sense, including tabular data, strings, user actions (for example, clicking a button), images, and any form of data with information. The job of our code is to process various forms of data and render them in the way you want.

In order to do our work, we 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 very straightforward-we wrap the data with specific objects. More specifically, objects can hold data (for example, properties) and can manipulate data (for example, 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. We can use the built-in str class to wrap string data, which not only allows us to pass string data using string objects, but also changes the representation of strings. Let's see a very simple example below.

> > # create a variable of type str. Hello = "Hello Python!". # send data to a function call. Print (hello). # manipulate string data using the string method. Hello_lower = hello.lower ()... Hello_upper = hello.upper ()... Print ('lowercased:', hello_lower)... Print ('uppercased:', hello_upper)... Hello Python! Lowercased: hello python! Uppercased: HELLO PYTHON!

2.DRY (do not repeat)

The DRY principle (don't repeat) is one of the most basic rules that every programmer should practice. The rule is simple: if you notice any duplicates in your code, this is a signal that the code needs to be refactored, minimize duplicated code, or remove duplicate code as completely as possible. The pseudo code below shows you how to ReFactor some code by applying the DRY principle.

Def do_something (item): pass # repetitive work do_something (item0) do_something (item1) do_something (item2) # Application DRY for item in (item0, item1, item3): do_something (item)

Code refactoring has another application scenario: you 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, consider using your own classes to process the data. This is not only to reduce the possibility of code errors, but also to facilitate long-term maintainability.

3. PIP (Python package installer)

Perhaps the most important reason for Python's popularity is its open source nature, which has led to a steady stream 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.

# install the latest version of pip install package_name # install a specific version of pip install package_name==version_number # uninstall the package pip uninstall package_name # display the installed package pip list # display information about the specific package pip show package_name # install a list of dependencies, such as clone virtual environment pip install-r requirements.txt

4. LEGB (local, closed, global and built-in)

The LEGB rule refers to the variable lookup order 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 local scope, which can be a function or class. If the interpreter finds the corresponding bound value of the variable, it stops looking and uses the variable with that particular value.

Variable resolution rule

Otherwise, it will look for it at a higher level-the closed range. The closed scope exists only in the nested structure of the function. Specifically, when a function is declared in another function, we call the inner function the inner function and the outer function the outer function. When the interpreter tries to parse the variables used in the scope of the internal function, if it cannot be parsed in the local scope, it will go to the closed scope, that is, the local scope of the external function.

If it still cannot resolve variables in closed scope, it will go to the global scope. The global scope is usually module-level, usually a separate Python file. It is worth noting that when we import the package into the current file, the imported functions and classes will also become part of the global scope. Built-in scope refers to the functions, classes, and other modules that are loaded when the interpreter is started, so that these most basic objects are always available (such as printing 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 how they call methods or get specific properties. MRO is mainly discussed in the context of multiple inheritance-classes that inherit from multiple classes (that is, superclasses) and / or classes that inherit from multiple layers (that is, subclasses). Because both subclasses and superclasses share common methods that implement methods that may be different, the Python interpreter needs a mechanism to determine which method or property should be used in a particular call, which is the responsibility of MRO. The following code snippet shows a schematic example.

Class X:... Def bin (self):... Print (f "bin called in X"). Class Y (X):... Def go (self):... Print (f "go called Y"). Class Z (X):... Def go (self):... Print (f "go called Z"). Class W (Y, Z):... Def bin (self):... Super (). Bin ()... Print (f "bin called W"). Def bingo (self):... Self.bin ()... Self.go (). W = W (). W.bingo ()... Bin called in X bin called W go called Y

For an instance of class W (line 22), when we call the bingo () method, this method will be resolved 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 parses on its own class, but it calls the superclass's bin () method, as shown in line 15. However, in its direct superclass (that is, Y and Z), the bin () method is not implemented, so Python is one level higher than the superclass (that is, X) of the superclass, implementing and calling the bin () method in the superclass.

It is worth noting that for W's go () method, both of its superclasses implement this method, but as you can see, only the implementation used in the Y class is called. This is because when we define the W class, the inheritance order is Y and Z, which makes MRO follow the same order. In connection with this, we can use the special method _ _ mro__ to find the MRO of a particular class, as shown below. In addition, to show you the importance of the order of class inheritance, we created another class, where class Z comes before class Y, which changes the MRO of class W_.

> print ('W Class MRO:', W.roommate _). Class WZ, Y:... Pass...... Print ('W _ Class MRO:', Wend.roomproof _). W Class MRO: (,) W _ Class MRO: (,)

6.&7.EAFP (it is easier to ask for forgiveness than permission) and LBYL (look before you leap)

EAFP (it's easier to ask for forgiveness than to ask for permission) the coding style is where Python is booming. 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. Basically, our idea is that if something unexpected happens, we will deal with it afterwards.

Contrary to the EAFP principle, there is another coding style called LBYL, which stands for "leapfrog". With this coding, programmers should rule out all possible unwanted situations before some code can be run. Therefore, you can see more if statements that follow LBYL principles in the project. This kind of coding can basically prevent any problem in a special way.

The following code snippet shows you a possible scenario for using EAFP and LBYL. For the EAFP coding style, we only need to use the try... The code and expected possible exceptions are wrapped in the except statement, while for the LBYL coding style, we must use introspection and value checking to verify the applicable conditions before partitioning. As you can see, the EAFP code looks cleaner and does not create a nested structure. Of course, you can also apply LBYL to the project if you like, and it won't change the way the project ultimately works.

Def with_EAFP_divide_ten_by (number): try: print (Fair10 divided by {number} is {10 / number}.') Except ZeroDivisionError: print ("You can't divide zero.") Except TypeError: print ("You can only divide a number.") Def with_LBYL_divide_ten_by (number): if isinstance (number, int) or isinstance (number, float): if number = 0: print ("You can't divide zero.") Else: print (frank10 divided by {number} is {10 / number}.') Else: print ("You can only divide a number.")

8. PEP (Python enhancement recommendation)

In the previous section, we discussed the coding style. However, 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 everything related to Python. You can find the whole list on the official website. Here are some famous articles:

PEP 8:Python Code style Guide (https://www.python.org/dev/peps/pep-0008/)

PEP 257: document string conventions (https://www.python.org/dev/peps/pep-0257/)

The Zen of PEP 20:Python (https://www.python.org/dev/peps/pep-0257/)

PEP 498: text string interpolation (https://www.python.org/dev/peps/pep-0498/)

PEP 202: list understanding (https://www.python.org/dev/peps/pep-0202/)

PEP 405:Python virtual environment (https://www.python.org/dev/peps/pep-0405/)

9.BDFL (benevolent dictator of life)

What is BDFL? Of course, the title has told you what it stands for, but what does it actually mean?

On Wikipedia, it is defined as:

The benevolent Life dictator (BDFL) is a title given to a small number of open source software development leaders, who are usually the founders of the project who retain the final say in disputes or disputes within the community.

Although this definition generally applies to open source software development, it is first used in the Python community as a reference to Guido van Rossum (GvR), the creator of the Python programming language. After holding the position of BDFL for more than 20 years, he stepped down in 2018.

10. REPL (read-evaluate-print cycle)

In my opinion, REPL (read-evaluate-print cycle) is a convenient tool for us to learn Python so easily. As we know, we can even start learning Python programming as easily as using commands or terminal windows. You can install any software package using the pip tool as shown earlier. More importantly, we can write the first line of Python code immediately without having to configure any IDE tools in other programming languages.

> print ("Hello World!") Hello World! > 3 * 26 > type (5)

The REPL workflow is simple-- read the substitution code in the console, evaluate it, and print out any applicable results, and then repeat these three steps over and over again to explore the various features of Python. REPL is implemented as the default pattern in standard Python or other common Python development tools such as ipython, and ipython is the foundation of the famous Python learning and coding tool Jupiter Notebook.

At this point, I believe you have a deeper understanding of "what are the skills of Python abbreviations?" you might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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