首页 > 代码库 > 第六(关于class&module)

第六(关于class&module)

一、一个简单的类调用

#!/usr/bin/env python
#-*- coding:utf-8 -*-
#5188179
class Role(object):

    def __init__(self,Name,Weapon,LifeValue):
        self.name = Name
        self.weapon = Weapon
        self.LifeValue = LifeValue

    def BuyWeapon(self,weapon):
        print("%s buy %s " %(self.name,weapon))
        self.weapon = weapon

p1 = Role("ckl","B11",99)
t1 = Role("zld","B12",100)
print(p1.weapon)
print(t1.weapon)
p1.BuyWeapon("B44")
t1.BuyWeapon("B51")
print(p1.weapon)
print(t1.weapon)

二、关于module说明

2.1.xml

 1 #!/usr/bin/env python
 2 #-*- coding:utf-8 -*-
 3 
 4 
 5 读取xml文件,通过段落标识符
 6 import xml.etree.ElementTree as ET
 7 
 8 tree = ET.parse("test.xml")
 9 root = tree.getroot()
10 print(root.tag)
11 
12 for child in root:
13     print(child.tag,child.attrib)
14     for i in child:
15         print(i.tag,i.text)
16 
17 for node in root.iter(year):
18     print(node.tag,node.text)
19 
20 
21 
22 修改xml,给year字段加1
23 import xml.etree.ElementTree as ET
24 tree = ET.parse("test.xml")
25 root = tree.getroot()
26 
27 for node in root.iter(year):
28     new_year = int(node.text) + 1
29     node.text = str(new_year)
30     node.set("updated","yes")
31 
32 tree.write("test.xml")
33 
34 
35 
36 删除country字段中rank值大于50的
37 import xml.etree.ElementTree as ET
38 tree = ET.parse("test.xml")
39 root = tree.getroot()
40 
41 for country in root.findall(country):
42     rank = int(country.find(rank).text)
43     if rank > 50:
44         root.remove(country)
45 
46 tree.write(test.xml)
47 
48 
49 
50 创建xml
51 
52 import xml.etree.ElementTree as ET
53 new_xml = ET.Element("NameList")
54 name = ET.SubElement(new_xml,"name",attrib={"enrolled":"yes"})
55 age = ET.SubElement(name,"age",attrib={"checked":"no"})
56 sex = ET.SubElement(name,"sex")
57 sex.text = 33
58 name2 = ET.SubElement(new_xml,"name",attrib={"enrolled":"no"})
59 age = ET.SubElement(name2,"age")
60 age.text = 19
61 
62 et = ET.ElementTree(new_xml)
63 et.write(test.xml,encoding="utf-8",xml_declaration=True)
64 ET.dump(new_xml)

shelve

 1 #!/usr/bin/env python
 2 #-*- coding:utf-8 -*-
 3 #http://www.cnblogs.com/alex3714/articles/5161349.html
 4 #4963027
 5 
 6 import shelve
 7 d = shelve.open(ShelveTest)
 8 
 9 class Test(object):
10     def __init__(self,n):
11         self.n = n
12 
13 t = Test(123)
14 t2 = Test(112233)
15 
16 name = [ckl,zld,love]
17 d["test"] = name
18 d["t1"] = t
19 d["t2"] = t2
20 d.close()
21 
22 
23 
24 #json 模块
25 data = http://www.mamicode.com/{ckl:123,kaka:456}
26 import json
27 j_str = json.dumps(data)
28 print(j_str)
29 
30 with open(ckl.json,w) as fp:
31     json.dump(data,fp)
32 
33 
34 #shelve
35 
36 import shelve
37 s = shelve.open(test_shelve.db)
38 try:
39     s[key1] = {int:10,float:9.5,string:Sample data}
40 finally:
41     s.close()
42 
43 
44 import shelve
45 s = shelve.open(test_shelve.db,flag=r)
46 try:
47     existing = s[key1]
48 finally:
49     s.close()
50 print(existing)
51 
52 
53 
54 import shelve
55 s = shelve.open(test_shelve.db,writeback=True)
56 try:
57     print(s[key1])
58     s[key1][new_value] = this was not here before
59 finally:
60     s.close()
61 
62 s = shelve.open(test_shelve.db,writeback=True)
63 try:
64     print(s[key1])
65 finally:
66     s.close()
67 
68 
69 import shelve
70 db = shelve.open("database","c")
71 db["one"] = 1
72 db["two"] = 2
73 db["three"] = 3
74 db.close()
75 
76 db = shelve.open("database","r")
77 for key in db.keys():
78     print(repr(key),repr(db[key]))
79     #print(key)
80 db.close()

logging

 1 #!/usr/bin/env python
 2 #-*- coding:utf-8 -*-
 3 
 4 import logging
 5 
 6 记录特别级别以上的日志
 7 logging.warning("user [ckl] you are the best!")
 8 logging.critical("server is down")
 9 
10 
11 
12 记录日志到文件中
13 logging.basicConfig(filename=ckl06.log,level=logging.INFO)
14 logging.debug(this is a debug message!)
15 logging.info(this is a info message!)
16 logging.warning(this is a warn mesg!!)
17 
18 
19 
20 记录时间到日志
21 logging.basicConfig(format=%(asctime)s %(message)s,datefmt=%y/%m/%d %H:%M:%S,filename=ckl06.log,level=logging.INFO)
22 logging.warning(is this time to login?)
23 
24 
25 logger = logging.getLogger(ckl-log)
26 logger.setLevel(logging.DEBUG)
27 
28 ch = logging.StreamHandler()
29 ch.setLevel(logging.DEBUG)
30 
31 fh = logging.FileHandler("access.log")
32 fh.setLevel(logging.WARNING)
33 
34 formatter = logging.Formatter(%(asctime)s - %(name)s - %(levelname)s - %(message)s)
35 
36 ch.setFormatter(formatter)
37 fh.setFormatter(formatter)
38 
39 logger.addHandler(ch)
40 logger.addHandler(fh)
41 
42 logger.debug(debug message)
43 logger.info(info message)
44 logger.warn(warn message)
45 logger.error(error message)
46 logger.critical(critical message)

hashlib

 1 #!/usr/bin/env python
 2 #-*- coding:utf-8 -*-
 3 
 4 """
 5 learn hashlib module
 6 """
 7 """
 8 import hashlib
 9 m = hashlib.md5()
10 m.update(b"Hello")
11 m.update(b"It‘s me")
12 print(m.digest())
13 m.update(b"It‘s been a long time since last time we....")
14 print(m.digest())
15 print(len(m.hexdigest()))
16 """
17 
18 import hashlib
19 hash = hashlib.md5()
20 hash.update(badmin)
21 print(hash.hexdigest())
22 
23 hash = hashlib.sha1()
24 hash.update(badmin)
25 print(hash.hexdigest())
26 
27 hash = hashlib.sha256()
28 hash.update(badmin)
29 print(hash.hexdigest())
30 
31 hash = hashlib.sha384()
32 hash.update(badmin)
33 print(hash.hexdigest())
34 
35 hash = hashlib.sha512()
36 hash.update(badmin)
37 print(hash.hexdigest())
38 
39 import hmac
40 h = hmac.new(bckl)
41 h.update(bhellochen)
42 print(h.name)
43 print(h.hexdigest())

configparser

 1 #!/usr/bin/env python
 2 #-*- coding:utf-8 -*-
 3 
 4 import configparser
 5 config = configparser.ConfigParser()
 6 
 7 config["DEFAULT"] = {
 8     ServerAliveInterval:45,
 9     Compression:yes,
10     CompressionLevel:9
11 }
12 
13 config[bitbucket.org] = {}
14 config[bitbucket.org][user] = hg
15 config[topsecret.server.com] = {}
16 topsecret = config[topsecret.server.com]
17 topsecret[Host port] = 50022
18 topsecret[ForwardX11] = no
19 config[DEFAULT][ForwardX11] = yes
20 with open(ckl.ini,w) as configfile:
21     config.write(configfile)

 

第六(关于class&module)