python3.x Study Notes 2018-02-02 update

Source: Internet
Author: User
Tags abs

Preface: python3.x Part of the study notes, interested in exchanging learners can add WeChat:ywnlodaymzu5mtezmtq=. If the contents of the note are wrong, please point it out.
***

Operations on data types
    1. mutable data Types : Lists, collections, dictionaries
      List:
      ```
      Li=[' A ', ' B ']
      Increase:
      Li.insert (2, ' C ') #在序号2位置上插入 ' C '
      Li.append (' d ') #在列表末尾添加 ' d '
      Li.extend (LI2) #在列表li后面添加li2

By deleting:
Li.remove (' C ')
Del Li[2]
Li.pop (3)

Change:
Li[2]= ' C '
Li[1?? 1]= ' Ha '

Check:
Li.index (' C ')

Sort:
Sort (Key=lambda x:x[2],reverse=true)

集合:
Go back to the relationship test

S1={1,2,3,4,5},s2=set ([4,5,6,7,8])
S3=s1&s2 #求交集
S4=s1|s2 #求并集

字典:

a_dict={' name ': ' Alex ', ' age ': ' Sex ': ' Male '}
A_dict.get (' name ', ' wrong ') #找键名对应的值 to return the second argument if not found
A_dict.setdefault (' name ', ' Lema ') #查找该键, if not found, insert the key value pair
A_dict.update (DICT2) #将dict2添加到a_dict中

2. **不可变数据类型**:元组,字符串元组:` tuple1=(1,2,3,4,5) `字符串:

Str1= ' abcdef ', str2= "A|b|c|d"
Print (Str1.capitalize (), Str1.upper (), Str1.lower ()) #首字母大写, all caps, all lowercase
Print (Str1.find (str2,2,5)) #在str1中从序号2位置开始找str2 until the position of the ordinal 5
Print (Str1.center ()) #在字符串两边各添加20个 "
Print (Str1.startswith (' ab ') + ', ' +str1.endswith (' EF ')) #返回True或False
Print ('-'. Join ([' 2018 ', ' 1 ', ' 1 '))
Print (Str2.split ("|", 3)) #返回一个列表
Print (Str1.replace (' A ', ' a ', 1)) #把str1中的第1个a替换成A
Print (Str1.strip ()) #把str1两边的空白字符去掉

***###函数1. 高阶函数

def func (x,y,f):
Print (f)
Print (Type (f))
return f (x) +f (y)
Result=func ( -3,-2,abs)
Print (Result)

2. 装饰器不修改被装饰函数的源代码不修改被装饰函数的调用方式

def auth (func):
def wrapper (*args,**kwargs):
Username=input ("Username:"). Strip ()
Password=input ("Password:"). Strip ()
If "Lema" ==username and "qwert123" ==password:
Res=func (*args,**kwargs)
else:
Print ("wrong")
return res
Return wrapper

@auth
def index (X,Y,F):
Print (f (x) +f (y))
Print ("Welcome to MyBlog")
Return "OK"
Print (index ( -3,-4,abs))

3. **参数**关键字参数位置参数可变参数4. **特殊函数*****###面向对象1. **类**:

class people (object):
Name= "Yin" #类变量
def Init(self,name,age=6): #构造函数
Self.name=name #实例变量self. Name
def del(self): #析构函数, executes this function when the instance object is garbage collected
Print ("End")
def sleep (self):
Print ("%s:hello,world"%self.name)
D1=people ("D1", age=5)
Del D1,people

2. **继承**:重写父类方法重构父类方法

Class Man (People):
#第一种重构方式
def sleep (self):
People.sleep (self)
Print ("Chonggou")
#第二种重构方式, it is recommended to use the second
def sleep (self):
Super (Man,self). Sleep ()
Print ("Chonggou")

多继承父类方法查询策略:广度优先

Class A (object):
def func (self):
Print ("A")
Class B (A):
# def func (self):
# print ("B")
Pass
Class C (A):
def func (self):
Print ("C")
def f (self):
Print ("1000")
Class D (B,C):
def func (self):
Super (D,self). Func ()
Super (D,self). F ()
Print ("D")
D=d ()
D.func ()

3. **多态**:一种接口,多种实现4. **方法**静态方法` @staticmethod `:名义上归类管理,实际上访问不了类和实例中的任何属性类方法` @classmethod `:只能访问类变量,不能访问实例变量属性方法` @property `:把一个方法转换成静态属性

class Person (object):
def Init(self,first_name,last_name):
Self.first_name=first_name
Self.last_name=last_name
@property
def full_name (self):
Return "%s%s"% (Self.first_name,self.last_name)
@full_name. Setter
def First_namex (self,first_name):
Self.first_name=first_name
P1=person ("Mike", "Driscoll")
Print (P1.full_name)
p1.first_namex= "Lema"
Print (P1.full_name)

伪私有方法:
A class method name that begins with a double underscore, which is automatically conceptually after the class instantiation, preceded by the name of the _ class. Because the name has been changed, so nature can not be accessed with the name of the beginning of the double row, so as to achieve the purpose of non-entry

class Person (object):
def __func (self):
Pass
P1=person ()
P1._person__func ()

` 类名.__doc__ `:返回该类的注释说明` __module__ `` __class__ `` __call__ `` def __str__(self): pass `:

Class Dog (object):
def Init(self):
Print ("Execute init")
def str(self):
Return "Execute __str__"
D1=dog ()
Print (D1)

5. **反射**:hasattr,getattr,setattr,delattr

def bulk ():
Print ("Add a function to the instance object")
Class Dog (object):
def Init(self,name):
Self.name=name
Def eat (Self,food):
Print (self.name+ ":" +food)
D1=dog ("Lema")
Choice=input (">>:"). Strip ()

The reflection is the function

If Hasattr (d1,choice): #hasattr判断一个对象里是否有字符串对应的方法属性
Func=getattr (D1,choice)
Func ("Rice")
Else
SetAttr (D1,choice,bulk)
D1.talk () #假设输入的是talk

Reflected is the attribute

Print (D1.name)
If Hasattr (d1,choice):
Attr=getattr (D1,choice)
SetAttr (D1,choice, "Ronghua")
Else
SetAttr (d1,choice,22)
Print (D1.name) #假设输入的是name
Print (d1.age) #假设输入的是age

***###模块1. **内置模块(标准库)**sys

Import Sys
Print ("Script name:", Sys.argv[0])
For i in Sys.argv[1:]:
Print ("parameter", i)

Exit the program and return to 0 for normal exit

Sys.exit (0)

Standard input

For line in Sys.stdin:
Print ("ABC", line)

time/datatime

Import Time,datatime
Time.sleep (0.5)
Today=datetime.date.today ()
Print (str (today.year) + '-' +str (today.month) + '-' +str (today.day))
Now=datetime.datetime.now () #now. Minute,now.day.now.second ...

random

Import Random

Randomly generate four-bit verification code

Checkcode= ""
For I in range (4):
Checkcode+=random.choice ("1234567890")
Print (Checkcode)
Print (Random.randint (11,13)) #生成11或12或13
Print (Random.randrange (2,10,2)) #生成2, 4,6,8

Disrupting elements

li=[1,2,3,4,5,6,7,8]
Random.shuffle (LI)
Print (LI)

hashlib

Import Hashlib
M1=HASHLIB.MD5 ()
M1.update (b "admin")
M1.update (b "123")
Print (M1.hexdigest ())
M2=HASHLIB.MD5 ()
M2.update ("admin123". Encode ())
Print (M2.hexdigest ())

re

Import re

Re.match () starts from the initial position of the string, and returns none if the initial position starts matching error

Print (Re.match ("chen\d+", "rchen321"))
Print (Re.match ("chen\d+", "chen321"). Group ())

Re.search () finds from string global, matches only the first one found

Print (Re.search ("chen\d+", "rchen321"). Group ())

Detach string, return ["abc", "De", "F"]

Print (Re.split ("[0-9]+", "abc12de34f"))

Replace match to character, return "abc11de14f"

Print (Re.sub ("[0-9]", "1", "abc52de34f", count=3))

Returns all results found in list form

Print (Re.findall ("chen\d+", "chen321 chen14"))

os

Import Os,os.path

Os.popen () returns a File object

Cmd_res=os.popen ("dir"). Read ()
Print (Cmd_res)

Determine if a file or directory exists

Print (Os.path.exists ("test.py"))
Print (Os.path.exists ("D:\software\Anaconda"))
Print (Os.path.isfile ("test.py"))
Print (Os.path.isdir ("D:\software\Anaconda"))

Path stitching

Print (Os.path.join ('/home/aa ', '/home/aa/', '/home/aa/bb/c '))

Detach path from extension

Print (Os.path.splitext ("/home/haha.py")) # Returns a two-tuple

Get the size of a file

Print (Os.path.getsize ("test.py"))

Get System state information for related files, st_atime,st_mtime,st_ctime ...

Print (Os.stat ("test.py"). St_size)

Convert relative paths to absolute paths

Print (Os.path.abspath (file))

2. **第三方库(开源模块)**3. **自定义模块**4. 导入模块与导入包的区别:导入包的本质就是解释包下面的` __init__.py `文件导入模块有以下几种方式:

Import Module1_name,module2_name
From module_name Import * #不推荐使用
From random import Randint as Ri
From module_name import Func1,func2

Dynamic load Module

mod1=Import("Baobao.test")
Print (MOD1)
Mod1.test.func ()

The official recommendation uses the following usage

Import importlib
Mod2=importlib.import_module ("Baobao.test")
Print (MOD2)
Mod2.func ()

***###文件处理1. **文件读取&写入**

With open ("Test.txt", "r+", encoding= "Utf-8") as F:
F.write ("hello456\n")
F.writelines (["Hello", "world", "\ n"])
#逐行读取文本内容
For line in F:
Print (line)
#一次性读取当前光标后的10个字符
Print (F.read (10))
Print (F.tell ()) #获得当前文件的光标
F.seek (0) #将光标移动到最开始的地方

2. **文件打开的模式**"r":只读模式"w":创建或覆盖模式"a":追加模式"r+":读写模式***###其它特性:1. **生成器**把列表生成式的[]改为()

[I*2 for I in Range (10000000)] #列表生成式, [func (i)-I in range (10)]
(I*2 for I in range (1000000)) #生成器

含yield的函数2. **迭代**可迭代对象:可以通过for循环来遍历的对象称为可迭代对象,比如str,dict,list,tuple,set,生成器迭代器:可以被next()函数调用并返回下一个值的对象称为迭代器,把可迭代对象变成iterator可以使用iter()函数3. **垃圾自动回收机制****del**:函数名,实例名,变量名,类名4. **异常处理**

data={}
li=[1,2]
Try
Open ("Test.txt", R)
data[' name ']
LI[3]
Except Keyerror as E:
Print ("Without this key", E)
Except Indexerror as E:
Print ("List operation error", E)
Except Exception as E:
Print ("Unknown error")
Else
Print ("Everything Works")
Finally
Print ("Execute as usual" with or without errors)

Custom exceptions

Class Alexexception (Exception):
def Init(self,msg):
Self.msg=msg
def str(self):
#print (SELF.MSG)
Return self.msg
Try
Raise Alexexception ("My Exception")
Except Alexexception as E:
Print (e)

Assertion

Num=13
Assert type (num) is str
Print ("right")

***###软件目录结构规范

Foo
Bin # contains executable files for some projects
Start. py with one click
Core # holds all source code for the project
Tests # Store Unit test Code
init. py
test_main.py
init. py
main.py
Docs # Storing some documents
conf.py
Abc.rst
setup.py # Installation, deployment, packaged scripts
Requirements.txt # List of external Python packages that store software dependencies
README #项目说明文件
1. Software positioning, basic functions of software
2. How to run the code, install the environment, start the command, etc.
3. Brief instructions for use
4. Code directory Structure Description
5. FAQ

###多线程&多进程

Import Threading,time
def run (N):
Print ("Task:", N)
Time.sleep (2)
Print (Threading.current_thread ()) # Returns the current thread object
Print (Threading.active_count ()) # Returns the number of currently surviving threads
Print (Threading.main_thread ()) # returns the main thread object
Start_time=time.time ()
T_total=[]
For I in range (50):
T2=threading. Thread (target=run,args= ("t%s"%i,))
T2.setdaemon (True) # Sets the current thread as the daemon thread
T2.start () # Main thread start child thread
T_total.append (T2)

For T in T_total:t.join () # One thread waits until another thread finishes executing the following code

End_time=time.time ()
Print (Threading.current_thread ())
Print (End_time-start_time)

Thread interaction

Import time,threading
Event=threading. Event ()
def lighter ():
Count=0
Event.set () # Set flag bit
While True:
If Count>5 and count<=10: # turn red
Event.clear () # Empty the flag
Print ("Red light Stop")
Elif count>10:
Event.set () # Turn Green
Count=0
Else
Print ("Green Line")
Time.sleep (1)
Count+=1
Light=threading. Thread (Target=lighter,)
Light.start ()
def car (name):
While True:
If Event.is_set ():
Print ("%s is driving"%name)
Time.sleep (1)
Else
Print ("%s is Waiting"%name)
Time.sleep (1)
Event.wait ()
Car1=threading. Thread (target=car,args= ("Mercedes-Benz",))
Car2=threading. Thread (target=car,args= ("Lamborghini",))
Car1.start ()
Car2.start ()

Queue queues. Queue (maxsize=0) Order first-in, first-out queue. Lifoqueue (maxsize=0) sequential in-first-out, last in Outqueue. Priorityqueue (maxsize=0) can set priority when storing data

Import queue
Try
Q=queue. Queue (maxsize=3)
Q.put ("D1")
Q.put ("D2")
Q.put ("D3")
Q.put ("D4", Block=false)
Print (Q.qsize ()) # return Queue Length
Print (Q.get ())
Print (q.get_nowait ())
Print (q.get_nowait ())
Print (Q.get (block=false))
Print (Q.get (timeout=3))
Print (q.get_nowait ())
Except queue. Empty as E:
Print ("Queue is empty")
Except queue. Full as E:
Print ("Queue full")

Q2=queue. Priorityqueue ()
Q2.put (( -2, "Lema"))
Q2.put (("ASD"))
Q2.put ((One, "qwe"))
Print (Q2.get ())
Print (Q2.get ())
Print (Q2.get ())
```

python3.x Study Notes 2018-02-02 update

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.