python总结(二)

1、类

学过面向对象编程的想必对类这个东西并不陌生,类是封装对象的属和行为的载体,比如说人类、鸟类,这些都是泛指一类。如果从人类中特指出一个人xxx,那xxx人必定会有人类这个类的相应的特征,xxx人就是一个对象,而由类到具体对象的过程称之为实例化。

1.1 类方法

方法可以理解为函数,在类中定义方法必须要加入参数self,它表示的是实例化的对象,如以下语句,表示为实例化添加静态的属性name

self.name = name  

除了上面的添加属性以外,还有一种添加属性的方法,不过有所不同

self.__age = age      //__age  实例化后不会被修改,要通过方法去改变,即实例化时传参

下面通过例子来看

class Student():
    def __init__(self,name,age):
        self.name = name
        self.__age = age
    def print_inform(self):
        print("name is %s" % self.name)
        print("age is %d" % self.__age)
user = Student("user1",15)
user.print_inform()
user.name = "Tom"
user.__age = 20
user.print_inform()
1.2 继承

继承就是提高代码重用度的一种方法,代码如下:

class Father():
    def __init__(self,name,age=30):
        self.name = name
        self.age = age
    def print_inform(self):
        print("name is %s" % self.name)
        print("age is %d" % self.age)
class Son_1(Father):           //继承父类的方法
    pass
class Son_2(Father):
    def __init__(self,name,age):
        super().__init__(name,age)
a1 = Father("Tom",60)
a1.print_inform()
a2 = Son_1("jon",15)
a2.print_inform()
a3 = Son_2("A",10)
a3.print_inform()

结果

name is Tom
age is 60
name is jon
age is 15
name is A
age is 10
2、 with

除了常见的使用with打开文件外,with最大的作用就是处理异常

class Test_with():
    def __enter__(self):
        print("start")
    def __exit__(self, type, value, trace):
        print("exit")
with Test_with():
    print("runing")

class Test_with():
    def __enter__(self):
        print("start")
    def __exit__(self, type, value, trace):
        if trace is None:
            print("exit")
        else:
            print("error is %s" % trace)
with Test_with():
    print("runing")
    raise NameError("testNameError")
3、并发
3.1 threading库
import threading
import time
from threading import current_thread
def Thread_test(arg1,arg2):
    print(current_thread().getName(),"start")  
    print("%s %s" %(arg1,arg2))
    time.sleep(1)
    print(current_thread().getName(),"stop")
for i in range(1,6,1):
    t1 = threading.Thread(target=Thread_test,args=(i,i+1))
    t1.start()
print(current_thread().getName(),"end")

结果

Thread-6 start
1 2
Thread-7 start
2 3
Thread-8 start
3 4
Thread-9 start
4 5
Thread-10 start
MainThread 5 6
end
Thread-6 stop
Thread-7 stop
Thread-8 stop
Thread-9 stop
Thread-10 stop
3.2 实现线程同步
import threading
from threading import current_thread

class Test_thread(threading.Thread):
    def run(self):
        print(current_thread().getName(),"start")
        print("run")
        print(current_thread().getName(),"stop")
t1 = Test_thread()
t1.start()
t1.join()
print(current_thread().getName(),"end")

结果

Thread-6 start
run
Thread-6 stop
MainThread end
4、时间 datetime and time
4.1 time库
>>> import time
>>> print(time.localtime())
time.struct_time(tm_year=2019, tm_mon=3, tm_mday=4, tm_hour=15, tm_min=34, tm_sec=1, tm_wday=0, tm_yday=63, tm_isdst=0)
>>> print(time.strftime("%Y-%m-%d"))
2019-03-04
4.2 datetime库
>>> import datetime
>>> print(datetime.datetime.now())
2019-03-04 15:36:05.637828
>>> newtime = datetime.timedelta(minutes=10)
>>> print(datetime.datetime.now()+newtime)
2019-03-04 15:47:29.401035
>>> one_day = datetime.datetime(2010,5,7)
>>> print(one_day)
2010-05-07 00:00:00
5、数学 math and random

math库可用于常见数学上的运算,如sin,cos等

https://docs.python.org/3/library/math.html

>>> import random
>>> print(random.randint(1,10))   //输出1~10的随机数
7
>>> print(random.choice(["a","b","c"])) //随机输出a,b,c
a
6、命令行 os
>>> import os
>>> print(os.path.exists("/user"))   //判断目录是否存在
False

https://docs.python.org/3/library/os.html

7、正则re

这一项我以前写过,在正则表达式

8、python-xml

xml 指可扩展标记语言,它是为了方便数据传输而设计的

<nodes>
        <node id="Use the DPID" name="host1" type="host" image="ubuntu:14.04">
            <ip>192.168.100.1</ip>
            <mac>Use the MAC address</mac>
        </node>

        <node id="Use the DPID" name="host2" type="host" image="nginx">
                <ip>192.168.100.2</ip>
                <mac>Use the MAC address</mac>
        </node>
   </nodes>

标签语言,有tag、attrib、text

import xml.etree.ElementTree as ET
tree = ET.parse('country_data.xml')
root = tree.getroot()
9、python-json
>>>import json
>>>data = json.loads(topo)    //loads中s代表string
>>>data = json.dumps(topo)
10、 subprocess
import subprocess
run(...): Runs a command, waits for it to complete, then returns a  CompletedProcess instance.
Popen(...): A class for flexibly executing a command in a new process


subprocess.Popen("D:\\Evernote\\Evernote\\Evernote.exe")
subprocess.Poprn("D:\\Python\\Python36\\python3.exe","C:\\hello.py")

Popen对象有两个方法poll()、wait()

11、 PIL

一个用于图片处理的库

from PIL import image
elem = Image.open("demo.jpg")
elem.size
elem.format
elem.filename

im = Image.new("RGBA",(100,200),"purple")
im.save("purple.png")
12、参考链接

https://docs.python.org/3/library/index.html