面向对象操作
类 有对象 、属性、方法
class Cat(object): 定义类
print('this is a cat class')
name='fentiao'
age=10
weight=180 属性
fentiao=Cat() 创建对象
print(Cat,fentiao)
print(fentiao.name) 查看属性值
print(fentiao.age)
print(fentiao.weight)
/usr/local/bin/bin/python3.6 /root/PycharmProjects/untitled/day11/test1.py
this is a cat class
<class '__main__.Cat'> <__main__.Cat object at 0x7fc3ef6637b8>
fentiao
10
180
Process finished with exit code 0
面向对象的继承
class Cat(object):
def __init__(self,name,age,weight):
self.name=name
self.age=age
self.weight=weight
fentiao=Cat('fentiao',10,180) 示例化对象
print(fentiao.name)
print(fentiao.age)
print(fentiao.weight)
class Cat(object):
def __init__(self,name,age,weight):
self.name=name
self.age=age
self.weight=weight
def eat(self):
self.weight +=2
print('%s is eating,now weight is %s' %(self.name,self.weight))
fentiao=Cat('fentiao',10,180) 示例化对象
print(fentiao.name)
print(fentiao.age)
print(fentiao.weight)
fentiao.eat() 调用方法
fentiao.eat()
/usr/local/bin/bin/python3.6 /root/PycharmProjects/untitled/day11/test1.py
fentiao
10
180
fentiao is eating,now weight is 182
fentiao is eating,now weight is 184
Process finished with exit code 0
class Animals(object): 定义类
def __init__(self,name,age): 属性
self.name=name
self.age=age
def eat(self): 方法
print('%s is eating....' %(self.name))
class Cat(Animals): 定义类 父类 为 Animals
pass
class Dog(Animals): 定义类 父类 为 Animals
pass
a=Animals('dongwu',10) 实例化对象
a.eat() 调用方法
print(a.name) 查看属性
print(a.age)
class Animals(object):
def __init__(self,name,age):
self.name=name
self.age=age
def eat(self):
print('%s is eating....' %(self.name))
class Cat(Animals):
pass
class Dog(Animals):
pass
Cat 没有 __init__函数。则调用父类的构造函数,如果父类没有,就调用 父类的父类
fentiao=Cat('fentiao',10)
fentiao.eat()
print(fentiao.name)
print(fentiao.age)
class Animals(object):
def __init__(self,name,age):
self.name=name
self.age=age
def eat(self):
print('%s is eating....' %(self.name))
class Cat(Animals):
def eat(self):
print('cat %sis eating' %(self.name))
class Dog(Animals):
pass
fentiao=Cat('fentiao',10)
fentiao.eat()
print(fentiao.name)
print(fentiao.age)
多态,当父类和子类有同一方法时,优先执行子类的方法 自己和 父类都没有的方法,不能执行
/usr/local/bin/bin/python3.6 /root/PycharmProjects/untitled/day11/test1.py
cat fentiaois eating
fentiao
10
Process finished with exit code 0
class Animals(object):
def __init__(self,name,age):
self.name=name
self.age=age
def eat(self):
print('%s is eating....' %(self.name))
class Cat(Animals):
def __init__(self,name,age,fishCount):
super(Cat,self).__init__(name,age) 父类的属性
self.fishCount=fishCount 新加的属性
def eat(self):
self.fishCount -=2
print('cat %s is eating,now have fish %s' %(self.name,self.fishCount))
class Dog(Animals):
pass
fentiao=Cat('fentiao',10,100)
fentiao.eat()
print(fentiao.name)
print(fentiao.age)
/usr/local/bin/bin/python3.6 /root/PycharmProjects/untitled/day11/test1.py
cat fentiao is eating,now have fish 98
fentiao
10
Process finished with exit code 0
新式类 的继承算法 广度优先算法
python3中 全部是新式类
class Book(object):
def __init__(self,name,author,state,BookIndex):
self.name=name
self.author=author
self.state=state
self.BookIndex=BookIndex
def __str__(self): 实质是对象的字符串显示,当str(对象名)会自动调用 print(对象名)也会自动调用
if self.state==0:
state='wen jie chu'
if self.state==1:
state='jie chu'
return 'Book(%s,%s,%s,%s)' %(self.name,self.author,state,self.BookIndex)
b1=Book('python','guido',0,'t345')
print(b1.name)
print(b1)
print(str(b1))
class Book(object):
def __init__(self,name,author,state,index):
self.name=name
self.author=author
self.__state=state 私有属性,类外部不能调用
self.index=index
def get__state(self): 私有方法 类外部不能调用
if self.__state==0:
return 'in'
if self.__state==1: 私有方法 类外部不能调用
return 'out'
def set__state(self,value):
if value in [0,1]:
self.__state=value
return True
else:
raise Exception('the state has been in [0/1]') 抛出异常
book1=Book('linux','lee',0,'t345') 实例化
# book1.__sate
print(book1.get__state()) 看结果
# book1.set__state(3) 修改参数
print(book1.get__state()) 看结果
/usr/local/bin/bin/python3.6 /root/PycharmProjects/untitled/day11/test2.py
in
out
Process finished with exit code
类 属性装饰器
class Book(object):
def __init__(self,name,author,state,index):
self.name=name
self.author=author
self.__state=state
self.index=index
@property 将 函数 变为 属性值
def state(self):
if self.__state==0:
return 'in'
if self.__state==1:
return 'out'
@state.setter
def state(self,value):
if value in [0,1]:
self.__state=value
return True
else:
raise Exception('lalala')
book1=Book('kinux','lee',0,'t456')
print(book1.state)
book1.state=1
print(book1.state)
class Date(object):
def __init__(self,year,month,day): self 是对象
self.year=year
self.month=month
self.day=day
def date_show(self): 定义了一个函数
print("""
year:%s
month:%s
day:%s
""" %(self.year,self.month,self.day))
@classmethod 类方法 传入 cls 实质是Date 类
相当于把多个属性用一个字符串表示 然后进行分离
def date_str(cls,str):
if '-' in str:
year,month,day=str.split('-')
if '/' in str:
month,day,year=str.split('/')
return cls(year,month,day)
@staticmethod 静态方法 python解释器 不会传入任何参数
def date_is_vaild(str):
if '-' in str:
year,month,day=map(int,str.split('-'))
if '/' in str:
month,day,year=map(int,str.split('/'))
return year>0 and 0< month <=12 and 0<day<=31
date1=Date(2018,6,8) 以 int 型数字实例化
date1.date_show()
date2=Date.date_str('2018-6-8') 以 str 型实力化
date2.date_show()
date3=Date.date_is_vaild('4/8/2018')
print(date3) 简易判断日期是否合法
升级的过程 最后一个 可以对传入的进行操作 也可以对结果进行操作
/usr/local/bin/bin/python3.6 /root/PycharmProjects/untitled/day11/test2.py
year:2018
month:6
day:8
year:2018
month:6
day:8
True
Process finished with exit code 0
class Date(object):
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
def get_date(self): 封装
return self.day
d1 = Date(2018, 6, 8)
class Date(object):
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
def get_date(self):
return self.day
d1 = Date(2018, 6, 8)
print(isinstance(5,int)) 5 是整形吗
print(isinstance(d1,Date)) d1 是 Date 类吗
print(isinstance('hello',(Date,str,Iterable))) hello 是Date 类 或字符串 或 可迭代吗
print(type(d1))
print(dir(d1)) 查看d1的用法
print(d1.__class__) 查看d1的类名
print(d1.__doc__) 查看d1的解释说明
print(d1.__dict__) 查看d1的属性 以字典的形式列出
print(hasattr(d1,'year')) 查看 d1 是否具有这个属性
print(getattr(d1,'year')) 查看d1 的 year 属性值
print(getattr(d1,'lala','no have')) 若没有属性 lalala 则输出 no have
print(d1,'year',2000) 修改属性值 为 2000
import os
def save_score(filename,score):
os.mknod(filename) 创建文件
print('chuan jian %s ok' %(filename))
with open(filename,'w') as f:
f.write(str(score))
print('write success')
save_score('score.txt',score=100)
/usr/local/bin/bin/python3.6 /root/PycharmProjects/untitled/day11/test3.py
chuan jian score.txt ok
write success
Process finished with exit code 0
import os
def save_score(filename,score):
try:
os.mknod(filename)
print('chuan jian %s ok' %(filename))
except FileExistsError:
捕获异常,当出现FileExitsError错误时,忽略该错误,不影响后面代码的执行
print('wen jian yi jing cun zai')
with open(filename,'w') as f:
f.write(str(score))
print('write success')
score=90
save_score('score.txt1',score)
import pymysql
pymysql.connect(host='172.25.254.110',
user='rng',passwd='westos',
db='westos',charset='utf8') 数据库连接
import pymysql
conn=pymysql.connect(host='172.25.254.110',
user='rng',passwd='redhat',
db='westos',charset='utf8')
cur=conn.cursor() 创建游标,为了给数据库 输入sql指令
insert_sqli='insert into linux values("user1","123")' 定义命令
print('do it:',insert_sqli)
cur.execute(insert_sqli) 进行命令的操作
conn.commit() 对数据库的操作进行提交
cur.close() 关闭游标
conn.close() 关闭数据库连接
import pymysql
conn=pymysql.connect(host='172.25.254.110',
user='rng',passwd='redhat',
db='westos',charset='utf8')
cur=conn.cursor()
for num in range(1000): 进行批量操作
username='user'+str(num+1)
insert_sqli='insert into linux values("%s","%s");' %(username,'000000')
print('do it:',insert_sqli)
cur.execute(insert_sqli)
conn.commit()
cur.close()
conn.close()
import pymysql
conn=pymysql.connect(host='172.25.254.110',
user='rng',passwd='redhat',
db='westos',charset='utf8')
cur=conn.cursor()
try:
insert_sqli='update linux set password=%s where username=%s;' 更新操作
update_li=[('666666','user'+str(num)) for num in range(20,999)]
cur.executemany(insert_sqli,update_li) 有多个时 +many
except Exception as e:
print('failue',e)
else:
print('victory')
conn.commit()
cur.close()
conn.close()
import pymysql
conn=pymysql.connect(host='172.25.254.110',
user='rng',passwd='redhat',
db='westos',charset='utf8')
cur=conn.cursor()
res=cur.execute('select * from linux;') 统计个数
print(res)
conn.commit()
cur.close()
conn.close()
import pymysql
conn=pymysql.connect(host='172.25.254.110',
user='rng',passwd='redhat',
db='westos',charset='utf8')
cur=conn.cursor()
res=cur.execute('select * from linux;')
print(res)
print(cur.fetchall()) 查看表的内容,以元组的方式
conn.commit()
cur.close()
conn.close()
import pymysql
conn=pymysql.connect(host='172.25.254.110',
user='rng',passwd='redhat',
db='westos',charset='utf8')
cur=conn.cursor()
res=cur.execute('select * from linux;')
print(res)
# print(cur.fetchall()) 查看所有
# print(cur.fetchmany(size=50)) 查看前50 个
print(cur.fetchone()) 查看第一个
conn.commit()
cur.close()
conn.close()
import pymysql
conn=pymysql.connect(host='172.25.254.110',
user='rng',passwd='redhat',
db='westos',charset='utf8')
cur=conn.cursor()
res=cur.execute('select * from linux;')
print(res)
print(cur.fetchmany(2)) 显示前两个
cur.scroll(-1,'relative') 根据当前位置 ,向左移动一个指针
print(cur.fetchmany(2)) 显示前两个
conn.commit()
cur.close()
conn.close()
/usr/local/bin/bin/python3.6 /root/PycharmProjects/untitled/day11/test4.py
1003
(('hello', '123'), ('user1', '123'))
(('user1', '123'), ('user1000', '000000'))
最终结果说明指针移动成功
Process finished with exit code 0
import pymysql
conn=pymysql.connect(host='172.25.254.110',
user='rng',passwd='redhat',
db='westos',charset='utf8')
cur=conn.cursor()
res=cur.execute('select * from linux;')
print(res)
print(cur.fetchall())
cur.scroll(1,mode='absolute') 绝对路径 向左右移动
print(cur.fetchone())
conn.commit()
cur.close()
conn.close()
import difflib 引用模块
def read_content(filename):
with open(filename) as f:
return f.read()
c1=read_content('t1')
c2=read_content('t2')
d=difflib.Differ() 实例化对象
print(d.compare(c1,c2))
for i in d.compare(c1,c2):
print(i) 显示 不友好
import difflib
import pprint
def read_content(filename):
with open(filename) as f:
return f.read()
c1=read_content('t1').splitlines()
c2=read_content('t2').splitlines()
d=difflib.HtmlDiff()
print(d.make_file(c1,c2))
执行结果倒入 访问即可看到
[root@foundation66 day11]# python3 test5.py > /var/www/html/hello.html