I'm learning Python In the process , Especially at the beginning of Xiaobai , There will be many " Other people's home " Glossy labels , Today, let's look at two common .
Zero basis
say " Zero basis " There are really many cases of , Originally Python Good command of programming , Say zero basic science , Instantly attract a crowd of white eyes , Especially with a career change 、 Interdisciplinary background .
Need to know , The zero basis of others , Maybe it's just that I haven't touched Python This language , But other programming languages are involved . Even if it's really a thorough foundation , You can't see his efforts behind his back . therefore , We should face it squarely " Zero basis " This tag , It can neither explain Python It's easy to learn , Nor can it prove who's strong or weak .
What about the zero basis , First of all, clarify each new learning Python All the people started from zero Foundation , There is no point in saying this . Learn from good examples Python It's not about your basic starting point , But in the reserve of knowledge 、 Application of methods and accumulation of practice .
Quick start
Generally follow closely " Zero basis " is " Quick start " This label is . With Python It has become more and more popular in recent years , train 、 Extension Python The copywriting of learning can be seen everywhere . With the starting point of zero Foundation , In addition, the final quick start has achieved the effect of promotion and salary increase , Isn't that what Python The best advertisement for training institutions ?
Python The simplicity of is compared with other programming languages , Not through learning time . Introduction to experienced programmers Python It can be weeks or even days , Pure Xiaobai may be confused for months or even years , Horizontal comparisons at different levels are meaningless .
Getting started quickly can be used to push yourself vertically : If you can , Don't revel in yourself , We should continue to deepen our study ; If you find it difficult to get started , Put your mind right 、 Slowly but surely . After you have a general grasp of your foundation and ability , Reasonable planning and efficient practice , Improve the quality of your study .
02
Combined with my own practice Python Experience , Recommend a learning method to Xiaobai's friends : When there is a need for ideas , Search for ready-made code to digest , Integrate and transform yourself . It sounds like absorbing other people's skills for yourself , So self styled " Star absorption method ".
Star absorption method
Each script has its own premise , For example, the sunflower classic " I want to practice this skill. , Must first **". We are not so strict , But we must learn to search efficiently .
Many, many Xiaobai won't search for questions , I'd rather spend a lot of time in the group 、 Go to the forum and ask questions , And don't look for answers directly through search engines , This is a big fear . meanwhile , Because it's really Xiaobai , You can't grasp the key points of the question when asking questions , After talking for a long time, others don't understand what you want , It's a waste of time .
Search for appropriate references , Read the code in combination with other people's explanations , After you understand it, integrate and transform yourself . First try to imitate learning , Digest a general idea, and then take the initiative to implement it with code .
The whole process comes down , We search and filter the results by ourselves , Study other people's complete code , Imitate, modify and integrate to form your own new code , The star sucking Dharma has been practiced .
Case drills
Just a few days ago, a friend asked to use Python Implement calculator , Let's use this question to practice the star sucking method .
The first is search , Demand is actually using Python Write Graphic interface Calculator , Search should reflect :
In addition, the selection of resources should be combined with personal needs , Because I've tried before tkinter To write a graphical interface , I'm going to take this opportunity to learn Qt Graphical interface programming , So I chose an article PyQt5 Implement the calculator article to learn .
https://blog.csdn.net/LindaMan_/article/details/81777543
The article is like a screenshot , stay csdn The code is posted on the blog with a more detailed description , Also posted its GitHub Code link . Here Xiaobai should pay attention , If you have a chance, get to know GitHub How to view the download code on , Try to upload your own code GitHub Share to practice . The code of the reference article is 200 Multiple lines , The first pile import It's completely incomprehensible , Especially bluffing . take it easy , Let's take a look and try to understand and absorb .
The first is the beginning import Area :
import sys from PyQt5.QtWidgets import (QMainWindow, QWidget, QApplication, QLineEdit, QPushButton, QGridLayout) from PyQt5.QtGui import QRegExpValidator from PyQt5.QtCore import Qt, QRegExp
first import sys, If you haven't touched before , You can search for the introduction sys Module contains and Python The interpreter's functions related to its environment . Three in a row PyQt5 dependent from import Obviously, it's the module we're going to use to construct the graphical interface , Let's not delve into the details first , Continue to look at the code .
class Calculator(QWidget): def __init__(self): def ui(self): def clear_line_edit(self): def deal_num_btn(self, sender_text): def deal_operator_btn(self, sender_text): def deal_point_btn(self): def deal_equal_btn(self): def show_msg(self): def auxiliary_calculate(self, first_num, second_num, operator: str): def calculate(self, operator='='):
Next, a long nearly 200 lines of code can sort out the above structure , In fact, it defines a class , Various functions are declared , We can also think that the code will instantiate this class and run it as a calculator object , To realize various functions of the calculator .
The last four lines of code , Is the command that the code actually executes :
if __name__ == '__main__': # be-all PyQt5 App must create an app (Application) object .sys.argv Parameter is a list of parameters from the command line app = QApplication(sys.argv) # cal It's the calculator we're going to build , It is Calculator An instance of a class cal = Calculator() # Calculator exit related sys.exit(app.exec_())
Tell the truth , When I went through the basics , Don't know __name__ This usage , What code to execute is written directly to run . This usage is mainly used to allow script modules to be imported into other modules , The script can also be executed by the module itself . That is, when this py When imported by other modules ,__name__ It's not “__main__”, Subsequent code will not be executed ; And when py When executed , Will trigger this condition to run its code directly .
The actual code executed , At first glance, it looks very complicated and can't understand , Analysis plus search , You can see that . Since you want to use PyQt5 To make a graphical interface application , Then we should form its style and function according to its format . As we expected , Would be right Calculator Class to instantiate , Then the function of the calculator is also prepared in the definition of a long series of classes above .
# QWidget yes Cal Parent class of class Calculator(QWidget): """ The basic interface of the basic page of the calculator , Complete basic calculations """ # __init__ Parameters passed in when creating an instance , Reference link https://www.cnblogs.com/illusion1010/p/9527034.html def __init__(self): #super() Function is used to call the parent class ( Superclass ) One way # Reference link https://www.runoob.com/python/python-func-super.html super(Calculator, self).__init__() # Here's the definition ui() function , The following will define self.ui() self.char_stack = [] # Stack of operands self.num_stack = [] # Stack of operands self.nums = [chr(i) for i in range(48, 58)] # Used to determine whether the value of the button is a number chr(48)-chr(57) Corresponding number 0-9 self.operators = ['+', '-', '*', '/','x^y'] # Used to determine whether the value of the button is an operator self.empty_flag = True # This flag It means to judge whether the calculator is started for the first time , There is no data in the display screen self.after_operator = False # Read the calculation of the calculator , such as 1+2 In the input + after ,1 It's also on the screen , Input 2 after ,1 It's replaced , This flag The function of is like this self.char_top = '' # Keep the operation symbol at the top of the stack self.num_top = 0 # Keep the value at the top of the stack self.res = 0 # Keep the calculation results , Look at the calculator and calculate once , Continue to press the equal sign , The last calculation will be repeated 1+2, obtain 3 after , Just press the equal sign 3+2, And so on . # > To calculate , Why is the same symbol changed to post calculation , To facilitate an operation , # It's after you calculate an expression , Continue to press and hold the equal sign , And will perform the last symbolic operation self.priority_map = { '++': '>', '+-': '>', '-+': '>', '--': '>', '+*': '<', '+/': '<', '-*': '<', '-/': '<', '**': '>', '//': '>', '*+': '>', '/+': '>', '*-': '>', '/-': '>', '*/': '>', '/*': '>' }
There are still some difficulties in this paragraph , for example class Calculator(QWidget) Is the form of inheriting the parent class ,__init__ in super() Calls to, etc . This paragraph is a unified definition and initial assignment for the variables and functions required by the calculator .
then ui() Relevant codes define the style and layout of the calculator graphical interface in detail , And bind the event triggered by clicking on the button in the interface . That is, when we click the calculator number button or operator , The number or operator will be displayed in the display box ; When you click “=” when , Will perform a series of operations and output the results .
The code download
Go through the source code in this order , Have a certain grasp of the overall idea and structure of the code . Suppose we want to add functionality to it , Just make the relevant changes in the function that adds the button or changes the layout , Then handle the bound click event properly , A calculator optimized by us was born .