python之day7(模块,面向对象)

今日上课的主要内容

一,模块:

二,面向对象(上):

作业(计算器):  

 http://www.cnblogs.com/wupeiqi/articles/4949995.html
  

模块:

configparser:都会按照字符串进行处理
       
import configparser

 

config = configparser.ConfigParser()

config.read('xxxooo', encoding='utf-8')

练习:

f1:

[section1]
k1 = v1
k2:v2

[section2]
k10 = v10
import configparser

config = configparser.ConfigParser()
config.read('f1',encoding='utf-8')

ret = config.sections()
print(ret)

ret = config.items("section2")
print(ret)

ret = config.options('section2')
print(ret)

v = config.get('section1', 'k1')
print(v)

has_sec = config.has_section('section1')
print(has_sec)

# config.add_section("section3")
# config.write(open('xxxooo', 'w'))
#
# config.remove_section("section3")
# config.write(open('xxxooo', 'w'))

has_opt = config.has_option('section1', 'k1')
print(has_opt)

config.remove_option('section1', 'k1')
config.write(open('xxxooo', 'w'))

config.set('section1', 'k10', "123")
config.write(open('xxxooo', 'w'))


XML:
浏览器返回的字符串
    1,html
    2,json
    3,xml
        页面上做展示(字符串类型的一个XML格式数据)
        配置文件(文件,内部数据XML格式)
        
    每一个节点都是 element的对象

练习1:

from xml.etree import ElementTree as ET
tree = ET.parse('xo.xml')
root = tree.getroot()
for child in root:
    print(child.tag,child.attrib)
    for grandchild in child:
        print(grandchild.tag,grandchild.attrib)

str_xml = open('xo.xml', 'r').read()
root = ET.XML(str_xml)
for node in root.iter('year'):
    new_year = int(node.text) + 1
    node.text = str(new_year)

    # 设置属性
    node.set('name', 'alex')
    node.set('age', '18')
    # 删除属性
    del node.attrib['name']

tree = ET.ElementTree(root)
tree.write('new.xml',encoding='utf-8')

tree = ET.parse('xo.xml')
root = tree .getroot()
for node in root.iter('year'):
    new_year = int(node.text) + 1
    node.text = str(new_year)

    node.set('age','18')
    node.set('name','sxl')

    del node.attrib['name']

tree.write('new2.xml',encoding='utf-8')

练习2:

from xml.etree import ElementTree as ET
from xml.dom import minidom

def prettify(elem):
    """将节点转换成字符串,并添加缩进。
    """
    rough_string = ET.tostring(elem, 'utf-8')
    reparsed = minidom.parseString(rough_string)
    return reparsed.toprettyxml(indent="	")

root = ET.Element('famliy')
son1 = ET.Element('son1',{'name':'大儿子'})
son2 = ET.Element('son2',{'name':'小儿子'})
grandson1 = ET.Element('grandson', {'name': '儿11'})
grandson2 = ET.Element('grandson', {'name': '儿22'})
son1.append(grandson1)
son2.append(grandson2)
root.append(son1)
root.append(son2)

raw_str = prettify(root)
tree = ET.ElementTree(root)
tree.write('oooo.xml',encoding='utf-8', short_empty_elements=False)
f = open("xxxoo.xml",'w',encoding='utf-8')
f.write(raw_str)
f.close()

 zipfile与tarfile

import zipfile
z = zipfile.ZipFile('xml.zip','w')
z.write('new.xml')
z.write('new2.xml')
z.close()

z = zipfile.ZipFile('xml.zip','r')
z.extract('new.xml')


import tarfile

z = tarfile.open('xml.tar','w')
z.add('new.xml','new_1.xml')
z.add('new2.xml','new_2.xml')
z.close()


z = tarfile.open('xml.tar','r')
print(z.getnames())
res = z.getmember("new_2.xml")
z.extract(res)

subprocess:

import subprocess
ret = subprocess.call("dir", shell=True)
print(ret)

ret = subprocess.check_output("dir C:", shell=True)
print(ret)

ret = subprocess.check_call("dir C:", shell=True)
print(ret)

######################################
com = subprocess.Popen("ls", shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
send_data = com.stdout.read()
sta_er = com.stderr.read()
send_data = str(send_data, encoding='gbk')
return send_data

shutil:
    http://www.cnblogs.com/wupeiqi/articles/5501365.html
    拷贝文件.

*面向对象

python 函数式+面向对象
函数式编程,面向对象编程实现:发送邮件的功能
    #函数
    def mail(email,message):
        print("去发吧")
        return True
    mail('alex3714@126.com','好人')
    
    面向对象:类,对象
    
    class Foo:
        #方法
        def mail(self,email,message):
            print('去发吧')
            return True
    
#调用
1 创建对象,类名()
obj = Foo()


2 通过对象去执行方法
obj.mail('alex3714@126.com','好人')

3 类和对象
    a创建类
        class 类名:
        
            def 方法名(self,xxxx):
                pass
    b创建对象
        对象 = 类名()
        
    c通过对象执行方法
        对象.方法名(123)

4

	#函数式:
		def fetch(host,username,password,sql):
			pass
		def create(host,username,password,sql):
			pass
		def remove(host,username,password,nid):
			pass
		def modify(host,username,password,name):
			pass
			
	#面向对象
		class SQLHelper:
			def fetch(self, sql):
				print(sql)
				print(self.hhost)
				print(self.uusername)
				print(self.pwd)
			def create(host,username,password,sql):
				pass
			def remove(host,username,password,nid):
				pass
			def modify(host,username,password,name):
				pass

		obj = SQLHelper()
		obj.hhost = 'c1.salt.com'      #变成self
		obj.uusername = 'alex'
		obj.pwd = '123'

obj.fetch("select * from A")
	

 ########》什么时候用面向对象?当某一些函数具有相同参数时,可以使用面向对象的方式,将参数一次性的封装到对象,以后去对象中取值即可。

5 self是什么鬼?
    self是一个python自动会给传值的参数
    那个对象执行方法,self就给谁
    obj2.fetch('....') self == obj2

6
    类中有一个特殊的方法 __init__,类()自动执行
    叫做构造方法。

  可以将用到的对象都写到这个函数里面。

class SQLHelper:
    def __init__(self,a1,a2,a3):
        self.hhost = a1
        self.uusername = a2
        self.pwd = a3

    def fetch(self, sql):
        print(sql)
        print(self.hhost)
        print(self.uusername)
        print(self.pwd)

    def create(host,username,password,sql):
        pass
    def remove(host,username,password,nid):
        pass
    def modify(host,username,password,name):
        pass
#
obj1 = SQLHelper('c1.salt.com','alex','123')        #self = obj1
obj2 = SQLHelper('c2.salt.com','alex','223')        #self = obj2

obj1.fetch('selcet * from A')
obj2.fetch('selcet * from A')

7 面向对象
    三大特性:封装,继承,多态

封装:

class c1:
    def __init__(self,name,obj):
        self.name = name
        self.obj = obj

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

    def show(self):
        print(self.age)

class c3:
    def __init__(self,aaa):
        self.a = aaa
c2_obj = c2('c2',19)
c1_obj = c1('c1',c2_obj)
#c2_obj.show()
# print(c1_obj.obj.age)
c3_obj = c3(c1_obj)            # aaa = c1_obj    c3_obj.a = c1_obj

c3_obj.a.obj.show()

python 继承

     -- 可支持多继承

class F1:            #父类,基类
    def show(self):
        print('show')
       
class F2(F1):        #子类,派生类
    def bar(self):
        print('bar')
    
    
多继承,左边的优先级高。会先继承优先级高的。往上找

class F1:
    def show(self):
        print('show')

    def Foo(self):
        print(self.name)

class F2(F1):
    def __init__(self,name):
        self.name = name

    def bar(self):
        print("bar")

F2_obj = F2('alex')
F2_obj.bar()
F2_obj.Foo()
原文地址:https://www.cnblogs.com/aaron-shen/p/5597913.html