In the distant kingdom of Python, there was a teenager who loved programming very much. His parents wanted to enroll him in a class. After asking their friends in the circle of almighty friends, they found that they all recommended the same teacher, named Mr. Ji.

So his parents did not hesitate to pay a large sum of tuition, every week six afternoon to let the child to study.

He worked very hard and quickly learned Python syntax, tools, and frameworks.

The teacher saw a beautiful jade that could be carved, and gave him all he could, telling him not only to write the code right, but also to make it beautiful, elegant, readable, and maintainable.

He also learned unit testing, TDD, refactoring, and trying to make his code meet the standards required by the teacher.

He also posted “Python Zen” on his wall, constantly checking his code and never breaking it.

The Zen of Python, by Tim Peters 

Beautiful is better than ugly. 

Explicit is better than implicit. 

Simple is better than complex. 

Complex is better than complicated. 

Flat is better than nested. 

Sparse is better than dense. 

Readability counts. 

.

Three years later, the boy thought he was a master of Python, until one day, his teacher gave him a big assignment. It was actually a big project, very complicated.

The boy stayed up all night programming, but he tragically found that no matter how hard he tried, his code was messy and unbeautiful, and his classes and modules were mixed up.

So he went to his teacher and said, “Sir, I’m pretty familiar with Python and the Flask framework. Why can’t I finish this project?”

The teacher said, “Kid, you only need to import the framework class and write a little code. Now you need to design the class by yourself and make the abstraction by yourself!”

“How do you design it?”

“My teacher will give you an ancient book, Design Patterns. Go back and have a good look at it.”

Young people like to win the treasure, sleep and forget to study this more than 20 years ago, yellowing ancient book, or C++ description.

He saw the clouds in the fog, seemed to understand, and did not seem to understand, had to ask the teacher again.

This time, the teacher gave him another book, Head First Design Patterns

The boy opened the book and saw that it was written in Java, so he plunged into the Java language.

This book is more easy to understand, the boy read the great shout.

Finally, he felt confident enough to start the big project in Python.

He used Python to implement design patterns and solve some design problems, but it felt strange compared to Java and C++.

In addition, he felt uncomfortable about dynamic language. Every time he wanted to reconstruct, he was always afraid to start. He told the teacher about his confusion.

The teacher laughed and said, “When I was in the Java kingdom, people always said, ‘Dynamic for a moment, rebuild the crematorium.’ Now you’ve got it!”

“Can Java avoid this problem?”

“Java is a static language, variable types cannot be changed once they are determined, and the support for refactoring is very good. Are you interested in checking it out? There are a lot of frameworks out there, like Spring, Spring Boot, MyBatis, Dubbo, Netty, that are thriving.”

Young heart yearning, so the teacher gave him to write a note, told him that the Java kingdom, find IO minister, everything will be unimpeded.

The boy said goodbye to the teacher and ran to the Java Empire. The teacher cleaned his clothes, looked at the direction of the Eastern Java Empire and solemnly bowed three times: “Five years, Lord IO, I did not live up to your great trust, and fooled another person to do Java!”

The teacher was Jason! The missionary sent by the IO minister to spread Java culture and values was discovered and put under house arrest in the Python kingdom.

For giessen’s story, can the Java Empire Succeed in Infiltrating Python?

King Python received a report from the border that a number of young people have recently gone to the Java kingdom. I don’t know if there is a change in domestic policy, which has caused the public sentiment to fluctuate.

King Python was furious and ordered a strict investigation. All the clues led back to one person: Giessen.

One day, the Python envoy took his soldiers to Giessen’s house, and sure enough, he found him fooling the young people again.

The envoy laughed angrily and said, “It is ridiculous that you, who have learned only half of Python, dare to demagogue people.”

Gisen remained calm when he saw that his ruse had been discovered. “I was teaching real object-oriented design and design patterns, which are awkward to implement in Python, so I recommended Java,” he said.

“Nonsense, how can writing design patterns in Python be awkward? Because Java is limited by syntax and has poor expression ability, some problems have to be solved with clumsy design patterns. Python can solve the problem at the syntactic level!”

“Tell me, what are the principles of design patterns?” Giessen asked.

“1. Program to the interface, not to the implementation. 2. Prioritize composition over inheritance.” This was difficult for the special envoy.

“How can you program to an interface when there are no Python connectors?” Giessen asked.

The envoy laughed and said, “You are half-skilled. You still believe that the interface here is your Java interface. Have you forgotten Duck Typing for Python?”

class Duck:    def fly(self):        print("Duck flying")class Airplane:    def fly(self):        print("Airplane flying")def lift_off(entity):    entity.fly()duck = Duck()plane = Airplane()lift_off(duck)lift_off(plane)Copy the code

“See, both Duck and Airplane don’t implement interfaces, but both call fly(). Isn’t that interface oriented programming? If you want to use an analogy, fly is an automated interface.”

Giessen really hadn’t thought of this layer, and as for the second principle, which prioritizes composition over inheritance, that could be implemented by any object-oriented language, he sighed and didn’t ask.

The envoy continued, “Duck Typing is very powerful. You mentioned design patterns. Let me give you an example, Adapter mode. Suppose the client has code that writes a log to a file.”

def log(file,msg):    file.write('[{}] - {}'.format(datetime.now(), msg))Copy the code

“Now we have a new requirement to write logs to the database, and the database does not have a write method, what if? Write an Adapter.”

class DBAdapter:    def __init__(self, db):        self.db = db    def write(self, msg):        self.db.insert(msg)Copy the code

“Note that this DBAdapter doesn’t need to implement any interface (I don’t have any in Python), just a separate class with a write method.”

db_adapter = DBAdapter(db)log(db_adapter, "sev1 error occurred")Copy the code

As long as there is a write method, no matter what object you are, you can call it, typical Duck Typing.

If Adapter can be written this way, the Proxy mode is similar. As long as your Proxy class has the same methods as the proxied class, it can be used by the client.

The downside of this approach, however, is that it is difficult to refactor the log method without knowing its parameter type.

Giessen challenged the envoy with another question: “How do you hide a class constructor and implement a singleton when Python doesn’t even have the private keyword?”

“Forget your Java mindset,” the envoy sniffed. “There are many ways to write a Singleton in Python. I’ll show you a Python way to do it.”

#singleton.pyclass Singleton: def __init__(self): Self. name = "I'm singleton"instance = singleton ()del singleton #Copy the code

Use the Singleton:

import singletonprint(singleton.instance.name)  # i'm singletoninstance = Singleton() # NameError: name 'Singleton' is not definedCopy the code

Giessen really didn’t think of writing it this way, using Python’s Modules to hide information.

Not every design pattern can do this, can it? Giessen thought to himself, and he had an incomprehensible model in mind: Visitor, which he had labored to learn.

Giessen said, “Tell me about Visitor, how do you use Python features?”

“I know what you’re thinking. You just want me to write a class and then write a Visitor to access it, right?”

class TreeNode: def __init__(self, data): self.data = data self.left = None self.right = None def accept(self, visitor): if self.left is not None: self.left.accept(visitor) visitor.visit(self) if self.right is not None: self.right.accept(visitor)class PrintVisitor: def visit(self,node): print(node.data)root = TreeNode('1')root.left = TreeNode('2')root.right = TreeNode('3')visitor = PrintVisitor()root.accept(visitor) # output 2, 1, 3Copy the code

Giessen said, “Yeah, isn’t that the Visitor pattern?”

“I’ll say you’ve only scratched the surface of Python. The essence of a Visitor is separating structure from operation, which can be done more elegantly in Python using a generator.”

class TreeNode:    def __iter__(self):        return self.__generator()    def __generator(self):        if self.left is not None:            yield from iter(self.left)         yield from self.data        if self.right is not None:            yield from iter(self.right) root = TreeNode('1')root.left = TreeNode('2')root.right = TreeNode('3')for ele in root:    print(ele)Copy the code

Admittedly, this approach is simpler to use and achieves a separation of structure and operation.

The envoy said: “See, Python at the language level provides support for some model, so a lot of design patterns in my big Python looks very awkward, we do not advocate here, of course we will grasp the SOLID object-oriented design principles and design patterns of thoughts, found and packaging changes, so you can write elegant program. “

Jisen sighed, feeling that he is not good at learning art, no longer resist, quietly captured.

The Python kingdom tried Giessen and was about to sentence him to death, but the Java Empire was heavily armed and demanded his release or war.

Giessen was sent back to the Java kingdom, where he became a hero, went home and compared Java with Python, and implemented Python on the Java virtual machine! In recognition of his heroism, the king named the language Jython.

Ps. This story inspired by the video: https://www.youtube.com/watch?v=G5OeYHCJuv0

If you can see this carefully, it shows that you are a die-hard supporter of the transformation of the code. Here are 5 copies of the “Head First Design Mode”, the signature version + the transformation of the code exclusive seal (thanks again for reader @aries’ hard carving).

Only five books, only by luck, in the public number reply message “design pattern lottery”, you can carry out the lottery.