程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Do you really understand Python naming?

編輯:Python

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 .

Legal variable name

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

Good variable names

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 .

Content

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 "
  • All three variables represent the user name
  • be relative to name, obvious username More effective information is transmitted
  • When your variable name contains enough valid information, it is a good variable name

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 "

form

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 "
  • lower_underscore: Lowercase letters followed by underscores
  • UPPER_UNDERSCORE: Capital letters followed by underscores
  • CamelCase: The big hump in Hump naming , Distinguish words by capitalization
  • mixedCase: The small hump in the name of hump , The difference with the big hump is that the first letter is lowercase

Recommended variable names

What are the recommended variable names ?

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 :

  • Python The naming conventions for libraries are a bit messy , So it will never be exactly the same
  • For all that , There are still currently recommended naming standards
  • New modules and packages ( Including third-party frameworks ) It should be written according to these standards , But if the existing library has a different style , Internal consistency is preferred

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 .

Python Variable format used in

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 )

Python Underline in “_”

Underline _

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

Pre underline prefix

stay Python in , Prepositional underscores may affect variables in terms of semantics and functions .

Single prefix _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 ")

Double leading underline __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

Post underline 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_

There are two underscores at the front and back __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.)

Other matters needing attention

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 .

Do you really understand Python Name it ? More articles about

  1. Step through these holes , Do you really understand python Basic ?

    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 ...

  2. You really will python Well ?

    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 ...

  3. python— Naming specification

    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. ...

  4. understand Python Naming mechanism

    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 ...

  5. python—— Double underlined and python Naming mechanism

    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 ...

  6. Do you really understand Redis Of 5 Is there a basic data structure ?

    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 ...

  7. [C#] C# Knowledge review - Do you really understand anomalies (Exception) Do you ?

    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 ...

  8. 【 turn 】 You really understand Python in MRO Algorithm ?

    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 ...

  9. python— Naming specification ( turn )

    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. ...

  10. 【 turn 】was mutated while being enumerated Do you think you really understand For...in... ??

    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 . ...

Random recommendation

  1. LoadRunner Script design 、 Scene design and result analysis

    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 :     ...

  2. delegate and event

    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 ...

  3. 51Nod Happy hand speed field 1 A Pinball[DP Line segment tree ]

    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 ...

  4. LinkedBlockingQueue Notes

    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 : ...

  5. linux bin &amp; sbin different

    linux bin & sbin different flutter & $PATH http://blog.taylormcgann.com/2014/04/11/differenc ...

  6. [ turn ] Use tee Record mysql client All operations , Ten time saving mysql command

    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 ...

  7. IE11 Out of commission F12 function DOM The resource manager cannot be used

    https://www.ludou.org/win7-ie-11-f12-bug.html 32 position win7 Download the patch :http://www.microsoft.com/zh-CN/download/de ...

  8. LeetCode--011-- Container for the most water (java)

    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 , ...

  9. Skype Server client policy parameter optimization

    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 ...

  10. Apache Performance configuration optimization

    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 ...


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved