Python self-use record

1. Python specification

Trample record:

1: After the class or function is defined, there should be 2 blank lines above and below
2: Add spaces on both sides of the operator, such as "="
3: l = get_size() When copying, there is a prompt ambiguous variable name 'l'(variable name'l' is not clear)
      solution: The characters l, O, I should be avoided as variable names, because these characters are easy to confuse people with the numbers 1, 0
4: #Get the screen size, the content on the left side of the comment prompt: block comment should start with #
      Solution: When commenting, add a space after # "# Get Screen size"
5: driver.swipe(x1,y1,x1,y2,1000), code hint: missing whitespace after","(","missing space after it)
      Solve: "," after adding a space, driver.swipe(x1, y1, x1, y2, 1000)
6: too many blank lines (3), there are too many blank lines on the upper and lower lines, there will be this prompt
7: print ('yes'), the prompt whitespace before "("
      solution: there is a space before the brackets, just remove the space
8 : Prompt no newline at end of file, because there is no newline character at the end of the file, just a newline at the end
9: print("His height is %f "% 1.833), prompt: missing whitespace around operator(missing spaces around the operator)
        Solution: ("%) is changed to ("%) That is
10:Class test6 is a prompt to create a class Class names should use Camelcase convention(the class name should use the camelcase convention)
        Solution: the first letter of the class name is capitalized, test6 is changed to Test6
11: The variable Threads = [] is defined in the function, and the prompt: Variable in function should be lowercase(The variable in the function should be lowercase)
        Solution: The first letter of the variable is lowercase threads = []
12: def t(): There are variables in the function t, prompt: Shadows name ' t' from outer scope(the shadow name "t" from the external scope), the variable inside the function, if the same as the external variable called by the function, will be PyCharm called the shadows name in
this case, it is apt to cause not easily perceived, some problems due to the consistent internal functions and external variables were triggered, so ensure to ensure internal functions and external variable names do not repeat to
        solve: function def t()changed def th()Or modify the name of the variable inside the function

Record collection:
¥ no space before the closing parenthesis
¥ comma, colon, semicolon do not add spaces before
¥ no space before the opening parenthesis of the function. For example, do not add a space before the opening parenthesis of Func(1)
¥ sequence. The List [2]
¥ left operator each with a space, not in order to align the increased space
¥ about default function arguments using the assignment operator without spaces
¥ IF / for / the while statement, even if the statement is executed only one, must separate line

2. Time module

1. Get the current time

from datetime import datetime

print(datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])

datetime.utcnow(): current time
strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]: format the time format, and the last three digits are not displayed


#Output : 2019-07-01 06:13:35.306

2. Format

import datetime
now = datetime.datetime.now()
print(now.strftime('%Y'+'%m'+'%d'+'_'+'%H'+'%M'+'%S'))  

#输出:
20190711_135732
   

3. Supplement

import datetime
now = datetime.datetime.now()

#假设时间为:201391721106秒
now.strftime('%Y')
'2013'

now.strftime('%y')
'13'

now.strftime('%H')
'21'

now.strftime('%M')
'10'

now.strftime('%S')
'06'

3. Wait

# 1
from time import sleep

sleep(0.5) #等待0.5sleep(1) #等待1秒

#2
import time

time.sleep(0.5) 

# 还可以把它赋给一个本地的名称
x = time.sleep
x(1)   # 与time.sleep(1)效果一样 

When to use it: generally used when waiting for the page to load

4. Print formatted output (% occupancy)

# %s打印字符串
# %s占位 ,  % 后面内容输出在占位%s位置
print("His name is %s, he is boy !" % "Aviad")
name = Aviad
print("His name is %s, he is boy !" % name)
#输出结果:
His name is Aviad, he is boy ! 
His name is Aviad, he is boy ! 

# %d打印整数
print("He is %d years old " % 2)
#输出结果:
He is 2 years old 

# %f打印浮点数
print("His height is %f " % 1.833)
print("His height is %.2f " % 1.833) # %.2f 指定保留小数点后2位数
#输出结果:
His height is 1.833000 
His height is 1.83 

#以下方法对%s,%d,%f都有效
#%2s意思是字符串长度为2,当原字符串的长度超过2时,按原长度打印,所以%2s的打印结果还是Aviad 
print("His name is %2s, he is boy !" % "Aviad")
#输出结果:
His name is   Aviad, he is boy !

#%7s意思是字符串长度为7,当原字符串的长度小于7时,在原字符串左侧补空格
print("His name is %-7s, he is boy !" % "Aviad")
#输出结果:
His name is   Aviad, he is boy ! 

#%-7s意思是字符串长度为7,当原字符串的长度小于7时,在原字符串右侧补空格
print("His name is %-7s, he is boy !" % "Aviad")
#输出结果:
His name is Aviad   , he is boy ! 

5. Module import

The test6.py code is as follows:

x = "tester"


def name():
    print("test6")


name() 

# 执行文件本身test6.py 输出为:
test6

The test7.py code is as follows:

from test6 import x


def boy():
    print('he is a ' + x)


boy()

# 执行文件本身test7.py 输出为:
test6
he is a tester

Conclusion: It can be seen that test7.py only calls the variable x in test6.py, but the output of test6.py is output when test7.py is executed name(), because when a module is first introduced by another program, its main program will run. If we want a certain program block in the module not to be executed when the module is introduced, we can use the __name__ attribute to make the program block execute only when the module itself is running.
Test6.py code modification:

x = "tester"


def name():
    print("test6")


if __name__ == '__main__':
    name()

At this time, the output of test7.py is as follows:

he is a tester

So, if __name__ == '__main__'the meaning is: when the .py file is run directly, if __name__ == '__main__'the code block below will be run; when the .py file is imported as a module, if __name__ == '__main__'the code block below will not be run.

6. Class

1. Create the Student class, capitalize the first letter of the class name, (Object) indicates which class the class inherits from, the Object class is a class that all classes will inherit

class Testers(object):
    pass

2. Instance: After the class is defined , an instance of Student can be created through the Student class. The creation of the instance is achieved by class name + ():

testers = Testers()

3. The class acts as a template, and necessary attributes can be added at the same time as it is created. Use the built-in method __init__, for example, bind the name and age attributes when creating the Testers class

class Testers(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age

# 上方代码中,self就是指类本身,self.name就是Testers类的属性变量,是Testers类所有。
# name是外部传来的参数,不是Testers类所自带的。
# self.name = name的意思就是把外部传来的参数name的值赋值给Testers类自己的属性变量self.name

    def hello(self):
        print('hello %s ,your age is %s' % (self.name, self.age))

# 在类中定义函数只有一点不同,就是第一参数永远是类的本身实例变量self,并且调用时,不用传递该参数。
# 除此之外,类的方法函数和普通函数没啥区别,你既可以用默认参数、可变参数或者关键字参数
# 这些封装数据的函数是和Testers类本身是关联起来的,称之为类的方法
# 补充:*args是可变参数,args接收的是一个tuple,**kw是关键字参数,kw接收的是一个dict

testers = Testers('luye', 18)
print(testers.name)
print(testers.age)
testers.hello()

# 输出结果:
luye
18
hello luye ,your age is 18

note:

  1. The first parameter of the __init__ method is always self, which represents the created class instance itself. Therefore, within the __init__ method, various attributes can be bound to self, because self points to the created instance itself.
  2. With the __init__ method, when creating an instance, you cannot pass in empty parameters. You must pass in parameters that match the __init__ method, but self does not need to be passed, and the Python interpreter will pass the instance variables in by itself .
  3. In Python, variable names are similar to __xxx__, which start with a double underscore and end with a double underscore. They are special variables. Special variables can be accessed directly, not private variables. Therefore, __name__ and __score_ cannot be used. _ Such variable names.
  4. Instance variable names that start with an underscore, such as _name, are accessible outside of such instance variables. However, according to conventional rules, when you see such a variable, it means, "Although I can be accessed, but , Please treat me as a private variable, don’t access it at will”.

6, the logging module reports an error

Error message: AttributeError: module 'logging' has no attribute 'basicConfig
Cause: The created Python file was named logging, and the same name as the logging module provided by the system caused the error.
Solution: Modify the .py file name

---------------------------------------------------------------------------------------------------------------------

Error message: TypeError: Level not an integer or a valid string: <function info at 0x0000027613AE1E18>
Cause: The keyword info in the code (logging.basicConfig(level=logging.info)) should be capitalized

import logging

logging.basicConfig(level=logging.info)
logging.debug('debug info')
logging.info('hello 51zxw !')
logging.warning('warning info')
logging.error('error info')
logging.critical('critical info')

Solution: change info to INFO

7. open() function: open the file and return the file object

Function description: The
Python open() function is used to open a file and return the file object. This function is required in the process of processing the file. If the file cannot be opened, an OSError will be thrown.

Note: Use the open() function to ensure that the file object is closed, that is, to call the close() function.

The common form of the open() function is to receive two parameters: file name (file) and mode (mode).
open(file, mode='r')

The complete syntax format is:
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

Parameter Description:

file: Required, file path (relative or absolute path).
mode: Optional, file opening mode
buffering: Set buffer
encoding: Generally use utf8
errors: Error level
newline: Distinguish line breaks
closefd: Incoming file parameter type
opener:

The mode parameters are:

mode description
t Text mode (default).
x Write mode, create a new file, if the file already exists, an error will be reported.
b Binary mode.
+ Open a file for update (read and write).
U Universal line break mode (not recommended).
r Open the file as read-only. The pointer of the file will be placed at the beginning of the file. This is the default mode.
rb Open a file in binary format for read-only. The file pointer will be placed at the beginning of the file. This is the default mode. Generally used for non-text files such as pictures.
r+ Open a file for reading and writing. The file pointer will be placed at the beginning of the file.
rb+ Open a file in binary format for reading and writing. The file pointer will be placed at the beginning of the file. Generally used for non-text files such as pictures.
w Open a file for writing only. If the file already exists, open the file and start editing from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file.
wb Open a file in binary format for writing only. If the file already exists, open the file and start editing from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file. Generally used for non-text files such as pictures.
w+ Open a file for reading and writing. If the file already exists, open the file and start editing from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file.
wb+ Open a file in binary format for reading and writing. If the file already exists, open the file and start editing from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file. Generally used for non-text files such as pictures.
a Open a file for appending. If the file already exists, the file pointer will be placed at the end of the file. In other words, the new content will be written after the existing content. If the file does not exist, create a new file for writing.
from Open a file in binary format for appending. If the file already exists, the file pointer will be placed at the end of the file. In other words, the new content will be written after the existing content. If the file does not exist, create a new file for writing.
a+ Open a file for reading and writing. If the file already exists, the file pointer will be placed at the end of the file. When the file is opened, it will be in append mode. If the file does not exist, create a new file for reading and writing.
from + Open a file in binary format for appending. If the file already exists, the file pointer will be placed at the end of the file. If the file does not exist, create a new file for reading and writing.

The default is text mode, if you want to open in binary mode, add b.

Example
Test file test.txt, the content is as follows:
RUNOOB1
RUNOOB2

f = open('test.txt')
 f.read()
 
 # 输出:
'RUNOOB1\nRUNOOB2\n'

open(“C:\Users\Spirit\Desktop\bc.txt”,‘r’) #会报错
由于python中的 ‘\’ 是转义符号,要想输出\ 的办法有两种:
1 、在\后再加\ 就是\ 的形式
把第二行改为infile =open(“C:\Users\Spirit\Desktop\bc.txt”,‘r’) 即可
2、在路径前加个 r ,意思是按原始字符处理 。
eg: infile =open(r"C:\Users\Spirit\Desktop\bc.txt",‘r’)
好的 文件就可以读取了!

8. format(): string formatting and filling

Built-in function of string type, used to format and fill the string, and return the processed string

# {}中无数字时起占位作用,传值按顺序从0开始升序
str = '一个篮子{}个鸡蛋,{}个篮子有{}个鸡蛋'
str.format(3,4,3*4)

# {}中有数字时,代表下标
str = '一个篮子{2}个鸡蛋,{1}个篮子有{0}个鸡蛋'
str.format(3*4,4,3)

# 输出结果一致:
一个篮子3个鸡蛋,4个篮子有12个鸡蛋

9, beautify json

import json

yhfc = {"测试": 1, "前端": 1, "后端": 2, "UI": 1}
print(json.dumps(yhfc))
print(json.dumps(yhfc, indent=4))     #  indent 美化输出时缩进占位数
print(json.dumps(yhfc, indent=4, ensure_ascii=False))   

# ensure_ascii默认为True,utf-8格式非ASCII编码内容会被编译成ASCII编码输出,要想得到字符的真实表示,需要设置为False

#输出:
{"\u6d4b\u8bd5": 1, "\u524d\u7aef": 1, "\u540e\u7aef": 2, "UI": 1}

{
    "\u6d4b\u8bd5": 1,
    "\u524d\u7aef": 1,
    "\u540e\u7aef": 2,
    "UI": 1
}

{
    "测试": 1,
    "前端": 1,
    "后端": 2,
    "UI": 1
}

10. range(): Produce a list of positive integers

range(起始值,结束值,低增值)
 起始值:可不填写,默认值为0
 低增值:可不填写,默认值为1
 range(100):0~99的整数
 range(1,100):1~99的整数

11. random(): Generate random data

import random
random.random() # 0-1的随机浮点数
random.rangint(a,b) # 最小值a-最大值b区间的整数
random.randrange(a,b,c) # 最小值a-最大值b区间按照c递增的整数
random.choice(a) # 从集合a中随机获取一个元素,a可以是字符串、元组、列表

12、assert、isinstance()

import time

def i_want_to_sleep(delay):
    assert(isinstance(delay, (int,float))), '函数参数必须为整数或浮点数'
    print('开始睡觉')
    time.sleep(delay)
    print('睡醒了')

if __name__ == '__main__':
    i_want_to_sleep(1)  # True
    i_want_to_sleep("666")  # False
'''
isinstance() 方法的语法: isinstance(object, classinfo)

参数:
object -- 实例对象。
classinfo -- 可以是直接或间接类名、基本类型或者由它们组成的元组。

返回值:
如果对象的类型与参数二的类型(classinfo)相同则返回 True,否则返回 False。
'''

Chapter 666: Commonly Used

s1 = {"1": 1, "2": "c"}
print(len(s1))
# 2

Guess you like

Origin blog.csdn.net/qq_38123721/article/details/94389694