Reprint please indicate the source ️
author : Test caituotuo
Link to the original text :caituotuo.top/7417a7f0.html
Hello everyone , I'm testing caituotuo .
today , Let's talk Python Name those things .
It is called the beginning of all things , All things begin without name , Dao begets One , One begets Two , Two begets Three , Our vision-be .
“ How to name variables ?”
It seems to be a very basic content , But there are still many people who are a little confused in this part .
Naming is often considered a detail in programming , Its importance is often underestimated . And the so-called craftsman spirit , Often reflected in the details .
Programmers have... In their work 80% Time spent reading and understanding code , Good naming can improve the readability and expressiveness of the code , Names that don't convey the meaning of words can be confusing , Add unnecessary thought overhead .
Learn from good examples Python, Start with variable naming .
What is a legal variable name ?
The so-called legal variable name is Python Variable names that the interpreter can recognize .
It is also a rule that must be followed in the coding process , Suppose you don't follow the rules , The program will report an error .
stay Python in , A valid variable name is given by Letter
、 Underline
and Numbers
form , And the first character cannot be a number .
stay Python3 in , The definition of letters is actually broad , You can write a Chinese variable name , In other words, you can think that the Chinese word is also a kind of letter , However, it is generally not recommended to use Chinese variable names , Because sometimes there may be some inexplicable... Due to some coding reasons bug.
caituotuo_666 = " Test caituotuo " # √
# 666caituotuo_666 = " Test caituotuo " # × The beginning of the number is illegal
Cai Tuotuo = " Test caituotuo " # √ Not recommended
Legal variable names obviously give us a lot of room to operate , We can take a variety of variables 、 Strange names .
What is a good variable name ?
A good variable name is a kind of Naming specification
, Although the naming convention is not followed , The program can still run , However, using naming conventions can more intuitively understand the meaning of the code , So with Python It is important that developers use the same naming system .
We can judge the quality of a variable name from its content and form .
From the perspective of content, it is how much effective information this variable name passes , Whether it is a meaningful variable name . Meaningful variable names can achieve the effect that the code is the document , High readability , There is no need for comments and documentation , The code itself can express the developer's intention explicitly .
For example, the following three variables :
n = " Test caituotuo "
name = " Test caituotuo "
username = " Test caituotuo "
however , The more effective information, the better , Obviously not , We also need to make a trade-off between valid information and variable name length ( The balance between the two depends on the project itself and the accumulation of experience ), Variable names should not be rounded to infinity in order to show more information , It is not an inch long and an inch strong , For example, the following variable name is too long
student_system_login_username = " Test caituotuo "
During coding , A variable name sometimes requires two or more words , When these words are crowded together , It's hard to tell who is who . So formally, we have four different ways to write variable names :
lower_underscore = " Test caituotuo "
UPPER_UNDERSCORE = " Test caituotuo "
CamelCase = " Test caituotuo "
mixedCase = " Test caituotuo "
Naming Convention Naming specification
stay PEP8 There are more detailed descriptions in it , Original address :https://peps.python.org/pep-0008/#naming-conventions
Naming Convention The core of consistency
( Uniformity )
The official meaning is probably :
When you see a variable name , How to quickly identify variables or Constant or class or function or …?
You need consistency , In other words, good variables don't just make your program look good , At the same time, it can also improve the programming efficiency .
stay Python There are three formats used in :lower_underscore、UPPER_UNDERSCORE、CamelCase, It won't use mixedCase.
lower_underscore: Lowercase letters followed by underscores ( Except constants and class names , All remaining names are lowercase underscores , Include :module modular
、variable Variable
、function function
、method Method
, They are Python Is usually used as a variable 、 Delivered , So they are named in the same way )
UPPER_UNDERSCORE: Capital letters followed by underscores , Only used to express Constant
( Actually in Python There are no real constants in , More is a kind of agreement , You don't move and I don't move , So when you want to express constants, you can use uppercase underscores , At the same time Python In the standard library, when you see the uppercase underline, you know that it is a constant )
CamelCase: The big hump in Hump naming , Distinguish words by capitalization , Only used to express class
mixedCase: The small hump in the name of hump , The difference with the big hump is that the first letter is lowercase ( Not in Python Use in )
_
stay Python Interpreter , There is a special feeling for single underscores .
Single underscores are also Python A valid variable name in , Usually used as a placeholder
for _ in range(5):
print(" Test caituotuo ")
for i in range(5):
print(" Test caituotuo ")
As can be seen from the above procedure , Use “_” Than using “i” Express more information , Is to tell others explicitly that this variable is useless .
_ Will point to the last expression you executed
Use a single underscore to format the value of a variable , For example, the amount , By this way we can make it easier to read
total_value = 8_000_000_000
print(total_value) # 8000000000
stay Python in , Prepositional underscores may affect variables in terms of semantics and functions .
_xx
Single underline in Python Medium name weak private (weak “internal use” ), Semantically, it expresses private nature , That is to say, it is not an open interface , When you use from module import * It won't import Of variables that begin with a single underscore , But it can still be used if you force it , So it is called weak private .
class MyClass:
def _get_name(self):
print(" Test caituotuo ")
def get_name(self):
print(" Test caituotuo ")
__xx
Corresponding to weak private is strong private , stay Python Of class definition It uses double pre underlined to indicate strong private , Forced quotation will result in an error , Can prevent being overridden by subclasses .
class MyClass:
def __get_name(self):
print(" Test caituotuo ")
In fact, strong private ownership can also be used , That is to say, a gentleman might as well be a villain ,Python It's actually in the class definition Rename the variables that begin with double underscores , Is to add a before the double downward stroke variable _class name
, If the print is obj._MyClass__get_name(), It still works
xx_
We know Python There are many key words in , for example :class、def、return、pass……, They all have special definitions and meanings , So we can't use them to name variables or methods when defining them , For example, the following code is wrong :
# Error model
def my_func(pass):
class = 1
return class
If that's how we want to define names , In order to distinguish between , You can add an underscore after ( However, it is not recommended to name it this way , Although it's legal , But there are so many names, why do you need to define keyword related names )
def my_func(pass_):
class_ = 1
return class_
__xx__
dunderscore:double underscore
To express specifically Python Magic function in magic method, It's all some Python Some built-in functions , We can take it and use it , for example : Class __init__
、__call__
etc.
about Python For users, do not use , Never use this form in your own defined method (Never invent such names; only use them as documented.)
Do not cover when naming Python Methods built into (builtin method)
# Error model
list = [1, 2, 3, 4] # ×
dict = {"username": " Test caituotuo "} # ×
str = " Test caituotuo " # ×
When naming a file , And don't follow the built-in module The nuptial , for example :os.py、selenium.py、turtle.py, It's not advisable .
One . Floating point calculation reflection 1: What is the result of printing ? a = 0.1 b = 0.2 c = 0.3 print(b == a + a) reflection 2: What is the result of printing ? a = 0.1 b = 0.2 c = 0.3 ...
Preface My blog has always been about technology sharing ,show code The place of , I've never written about personal life or emotional gossip , Of course, I've never talked about my likes and dislikes of anything . A lot of people like to spray XX Language , Like to talk about XX and YY The advantages and disadvantages of , I even got together ...
The file name is all lowercase , Underline can be used The bag should be short . Lowercase name . If underline can improve readability, you can add . Such as mypackage. Module and package specifications are the same as . Such as mymodule. Class always uses a string of uppercase words . Such as MyClass. ...
understand Python Naming mechanism This article was first published on the blog of lovebird (http://blog.csdn.net/lanphaday), Welcome to reprint , However, this statement must be retained and must not be used for commercial purposes . thank you . Introduction I warmly invite you to guess ...
python The function of double underline in (1) All members that begin with a double underscore are private (2)python For private variables, you can bind them (mangling) Of , The binding rule is the original definition :class A(): __function ...
Abstract : Do you really understand Redis Of 5 Is there a basic data structure ? Maybe you need to see these knowledge points . This article is shared from Huawei cloud community < Do you really understand Redis Of 5 Is there a basic data structure ? Maybe you need to see these knowledge points >, author : Li Ziba . One ...
Do you really understand anomalies (Exception) Do you ? Catalog Exception introduction Unusual features How to use exceptions Dealing with exceptions try-catch-finally Catch abnormal Catch block Release resources Finally block One . Abnormal medium ...
You really understand Python in MRO Algorithm ? MRO(Method Resolution Order): Method parsing order . Python Language contains many excellent features , Multiple inheritance is one of them , But multiple inheritance leads to a lot of ...
The file name is all lowercase , Underline can be used The bag should be short . Lowercase name . If underline can improve readability, you can add . Such as mypackage. Module and package specifications are the same as . Such as mymodule. Class always uses a string of uppercase words . Such as MyClass. ...
Original website :http://www.jianshu.com/p/ad80d9443a92 Support the original , If you want to reprint , Please indicate the source. Do you think you really understand For...in... ?? Ha ha ha ha , I also came across this error report . ...
This note mainly records LoadRunner Script design . Scene design and result analysis 1. Script design Recording mode Manual mode : Insert step . Write by hand 1.1 Script enhancement : ...
Events are special delegates entrust : The first method is to register with “=”, It's assignment syntax , Because to instantiate , The second way to register is “+=” The modifier should public When public, should private When private event ...
Pinball xfause ( Propositional person ) Base time limit :1 second Space restriction :262144 KB The score is : 20 Pinball The game interface of is composed of m+2 That's ok .n Column composition . The first line is at the top . A ball will start from a column in the first row ...
When looking at an audio transmission code recently , The other party adopted LinkedBlockingQueue For producers . Consumer model , To support read / write threads . I feel very good , Therefore, this method is also summarized , And a basic functional framework is combed . Two main points : ...
linux bin & sbin different flutter & $PATH http://blog.taylormcgann.com/2014/04/11/differenc ...
see :tail -f /tmp/jack.txt One :tee Method 1 . The configuration file is on the server /etc/my.cnf Medium [client] Join in tee =/tmp/client_mysql.log that will do . Method ...
https://www.ludou.org/win7-ie-11-f12-bug.html 32 position win7 Download the patch :http://www.microsoft.com/zh-CN/download/de ...
Given n Nonnegative integers a1,a2,...,an, Each number represents a point in the coordinate (i, ai) . Draw in coordinates n Bar vertical line , Vertical line i The two endpoints of are (i, ai) and (i, 0). Find two of them , ...
1.skype The principle of address book about skype Client's address book synchronization , First, let's talk about the principle , Address book information is from AD synchronous skype Front end servers ( Every day 1:30), On the client that is synchronized from the front-end server ( Probably 1 Sync once every hour ). skype ...
Preface It's been going on recently apache Performance optimization settings . In the revision apache To configure ) The original configuration folder needs to be backed up before the file conf, It's a good habit to set up a website . Following apache Configuration tuning is all in red had It's done in the environment of . htt ...
about Python I believe many pe
List of articles Method 1 :+