In fact, Python has great support for object-oriented programming, such as the Pathlib module (click link Review) we just introduced, which is a module that uses object-oriented thinking to handle file systems.

You can say that Python is “flexible and flexible”. It is easy to learn it out of the box when it is small and easy to learn it when it is serious.

But is object orientation always a good thing? Does it have to be used all the time to support object-oriented programming?

In the following paragraph from The Python Best Practices Guide, an open source project started and maintained by Kenneth Reitz (linked at the end), let’s take a look at the advice of God K.

The advice of Kenneth Reitz

Python is sometimes described as an object-oriented programming language. This may be misleading and needs to be clarified.

In Python, everything is treated as an object and can be treated as such. When we say that a function is a “first-order” object, we mean to treat a function as an object. Functions, classes, strings, and even types are objects in Python: Like any object, they have a type that can be passed as a function argument, and they may have methods and attributes. In this sense, Python is an object-oriented language.

Unlike Java, however, Python does not implement object-oriented programming as the primary programming paradigm. It is perfectly feasible for Python projects not to adopt an object-oriented approach, that is, to make little or no use of class definitions, class inheritance, or any other mechanism specific to object-oriented programming.

Furthermore, as you can see from the module section, the way Python handles modules and namespaces provides a natural way for developers to ensure encapsulation and separation of abstraction layers, both of which are the most common reasons for using object orientation. As a result, Python programmers have greater freedom not to use object-oriented programming when the business model does not require it.

For a number of reasons, we should avoid unnecessary object-oriented programming. Defining custom classes is useful when we want to glue some state and functionality together. In the discussion of functional programming, we pointed out that the problem of “unnecessary object-oriented programming” comes from the “state” section of the equation.

In some architectures, such as typical Web applications, multiple Python process instances are generated in response to external requests that may occur simultaneously. In this case, saving some state to the instance object means keeping some static information about the world, which is prone to concurrency or race problems. Sometimes, between the state of the object’s initialization (usually done with the __init__() method) and the state of the actual use of the object’s methods, the world information may have changed and the state maintained may be obsolete. For example, a request loads an item in memory and marks it for the user to read. Another request also asks for the item to be deleted, which might happen after the first process loads the item, and then we have to mark it as a deleted object.

These and other issues lead to the idea that using stateless functions is a better programming paradigm.

** Another way of saying this is to recommend using functions and programs with implicit contexts and side effects as little as possible. The implicit context of ** functions consists of global variables and data items (accessed using methods) in the persistence layer. Side effects are changes that a function makes to its implicit context. A function is said to have side effects if it saves or deletes global variables or data in the persistence layer.

Separating functions with context and side effects from logical functions (called pure functions) provides the following benefits:

  • Pure functions are deterministic: given a fixed input, the output is always the same.
  • Pure functions are easier to change or replace when they need to be refactored or optimized.
  • Pure functions are easier to test using unit tests: there is less need for complex context Settings and data cleanup afterwards.
  • Pure functions are easier to manipulate, modify, and pass.

In summary, for some architectures, pure functions are more efficient building blocks than classes and objects because they have no context or side effects.

Clearly, object-oriented programming is useful, even necessary, in many situations, such as when developing graphical desktop applications or games, where the things being manipulated (Windows, buttons, avatars, vehicles) have a relatively long life in computer memory.

Cat thought

That was God K’s advice. He mentions pure functions in the second half, which reminds Cat of Functional Programming, but pure functions seem to be a more general thing, like a mathematical definition. Are pure functions really so magical?

So, Maomao went to Google “pure function”. Surprisingly, the top results were all Javascript related.

Apart from the Wikipedia entry, the first answer pointed to a GitBook, THE JS Functional Programming Guide, which the curious cat clicked into and was amazed! I suggest you to read it if you have the conditions (see the link at the end of the article, do not understand JS does not affect understanding).

Coincidentally, the author of this book also shared his thoughts on object-oriented programming:

One of my favorite quotes comes from Joe Armstrong, author of the Erlang language: “The problem with object-oriented languages is that they always have to carry around those implicit environments. All you need is a banana and you get a gorilla with a banana… And the whole jungle.

After reading the chapter “The Benefits of pure functions”, Cat refined several notes. On the one hand, it is to strengthen the understanding of pure functions and avoid some “impure” usage in actual combat. On the other hand, it also puts forward several thoughts and questions. In the process of learning Python in the future, be careful to find the answer:

1. Avoid using impure functions. Splice is an impure function in JS. Is there one in Python?

2. The first one in the following example is impure because the result of the function depends on the variable minimum, in other words, it depends on system state. This is frustrating because it introduces an external environment that increases cognitive load. (Digression: This example, the cat has a lot of feelings. There is an old version of the company project code, full of various global variables, friends have a lot of trouble to maintain! Freeze can be used to make a minimum an immutable Object. Is there a similar implementation in Python?

Var minimum = 21; var checkAge =function(age) {
  returnage >= minimum; }; // Pure var checkAge =function(age) {
  var minimum = 21;
  return age >= minimum;
};
Copy the code

3. Impure functions can bring “side effects”. Their “effects” are not harmful in themselves, but their “side effects” are breeding grounds for bugs. This is not to say that all side effects should be banned, but that they should be controlled. Stick to the “same input, same output” principle.

4. A pure function is actually a function defined in mathematics. “A function is a special relationship between different values: each input value returns and only one output value.”

5. Reasons to pursue “pure” : cacheability (kind of like generator, delayed execution), portability/self-documentation (because it’s completely self-contained and has clear dependencies), testability (Quickcheck in JS, Python?) Rationality (quote transparency: a piece of code can be replaced with the result of its execution without changing the behavior of the entire program), parallel code (pure functions do not need to access shared memory at all, and pure functions do not enter a race condition due to side effects).

That’s all for today’s sharing, and a few more logical words. There is not a word of Python code in this article, which is pretty dry. Cats sometimes like to read such articles, because it will bring you the enlightenment of the mind, as if the supreme master is teaching the secret mind method. So, the cat also like paraphrased and thinking about this kind of problem, such as hair before a “super summary: learning Python list, this article only is enough”, is not only the content of the code level, had joined to Guido torre explanation about why Python list indices starting from 0, considering the index value and other programming language.

I do not remember where I have seen a sentence, sent to everyone to encourage:

What’s the difference between a man and a nong fish if all he can see is code?

The final final: because open late, the public number has no message function, if you feel that this article is helpful to you, welcome to support oh. Last PS: backstage reply “love learning”, get 20 selected e-books for free.

Read more:

Python best practices guide (in Chinese) : pythonguidecn readthedocs. IO/useful/latest /

Python Best Practices Guide: docs.python-guide.org/

JS: functional programming guide llh911001. Gitbooks. IO/mostly – at…


This article was first published on wechat public account [Python Cat]. The background replied “Love learning”, and you can get 20 selected e-books for free.