面向过程:
更具业务逻辑至上而下写代码
面向对象:
将Data与函数绑定在一起,进行封装,这样能够快速开发程序,减少重复代码和重写过程
类的组成
类的名称:类名
类的属性:一组Data
类的方法:允许对进行的操作的方法,行为
class Cat:
#属性
#方法
def eat(self):
print("猫在吃鱼")
def drink(self):
print("猫在喝水")
tom = Cat()
tom.eat()
>>>>
/usr/local/python3.6/bin/python3.6 /home/adapa/PycharmProjects/demo2/demo1.py
猫在吃鱼
#!/usr/bin/env python
#coding:utf-8
class Cat:
#属性
#方法
def eat(self):
print("在吃鱼")
def drink(self):
print("猫在喝水")
def ok(self):
print("tim:%s,tim age:%d" % (self.name, self.age))
tom = Cat()
#tom中添加属性
tom.name = 'tom'
tom.age = 40
tom.ok()
lanmao = Cat()
lanmao.name = 'lanmao'
lanmao.age = 26
lanmao.ok()
>>>
/usr/local/python3.6/bin/python3.6 /home/adapa/PycharmProjects/demo2/demo1.py
tim:tom,tim age:40
tim:lanmao,tim age:26
init方法 初始化对象
class Complex:
def __init__(self, realpart, imagpart):
self.r = realpart
self.i = imagpart
x = Complex(3.0, -4.5)
print(x.r, x.i) # 输出结果:3.0 -4.5
str 方法 对象描述信息
#!/usr/bin/env python
#coding:utf-8
class Cat:
"""定义了一个CAT类"""
#属性
def __init__(self,new_name,new_age): #初始化对象
self.name = new_name
self.age = new_age
def __str__(self):
return "这里是描述信息"
#方法
def eat(self):
print("在吃鱼")
def drink(self):
print("猫在喝水")
def ok(self):
print("tim:%s,tim age:%d" % (self.name,self.age ))
tom = Cat("tom",40)
tom.ok()
print(tom)
>>>
tim:tom,tim age:40
这里是描述信息
全局变量,函数,属性,方法的联系与区别
小测试1.烤地瓜
class sweetPotato():
def __init__(self):
self.cookedState = "生的"
self.cookeTime = 0
self.cookedzuoliao = []
def __str__(self):
return "红薯%s(%d)%s"%(self.cookedState,self.cookeTime,str(self.cookedzuoliao))
def cook(self,cooked_time):
self.cookeTime += cooked_time
if self.cookeTime >=0 and self.cookeTime<=3:
self.cookedState = '生的'
elif self.cookeTime >=3 and self.cookeTime<=5:
self.cookedState = '半生不熟'
elif self.cookeTime >=5 and self.cookeTime<=8:
self.cookedState = "熟了"
elif self.cookeTime >=8 and self.cookeTime<=9:
self.cookedState = "烤焦了"
elif self.cookeTime >=9:
self.cookedState = "烤湖了"
def addcookzuoliao(self,zl):
self.cookedzuoliao.append(zl)
#创建的第一个红薯对象
red_shu = sweetPotato()
red_shu.cook(1)
print(red_shu)
red_shu.cook(1)
print(red_shu)
red_shu.cook(1)
print(red_shu)
red_shu.addcookzuoliao("孜然")
print(red_shu)
red_shu.cook(2)
print(red_shu)
red_shu.addcookzuoliao("番茄酱")
red_shu.cook(2)
print(red_shu)
red_shu.addcookzuoliao("花椒")
print(red_shu)
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
/usr/local/python3.6/bin/python3.6 /home/adapa/PycharmProjects/demo2/demo1.py
红薯生的(1)[]
红薯生的(2)[]
红薯生的(3)[]
红薯生的(3)['孜然']
红薯半生不熟(5)['孜然']
红薯熟了(7)['孜然', '番茄酱']
红薯熟了(7)['孜然', '番茄酱', '花椒']
小测试2 存放家具
#!/usr/bin/env python
#coding:utf-8
class Home:
def __init__(self,acreage,info,region):
self.acreage = acreage
self.info = info
self.region = region
self.lit_acreaege = acreage
self.jiaju = []
def addjiaju(self,jiaju):
self.jiaju.append(jiaju.get_info())
self.lit_acreaege -= jiaju.get_acreage()
def __str__(self):
return "房子面积:%d,房子户型:%s,房子地址:%s,房子家具:%s,房子剩余面积:%s"%(self.acreage,self.info,self.region,self.jiaju,self.lit_acreaege)
class jiaju:
def __init__(self,acreage,info):
self.acreage = acreage
self.info = info
def __str__(self):
return "家具名称:%s,家具占地面积:%d"%(self.info,self.acreage)
def get_acreage(self):
return self.acreage
def get_info(self):
return self.info
fangzi = Home(126,"三室两厅","朝阳区 长安街 666号")
print(fangzi)
bad = jiaju(4,'原木床')
print(bad)
fangzi.addjiaju(bad)
print(fangzi)
sanfa = jiaju(6,'沙发')
print(sanfa)
fangzi.addjiaju(sanfa)
print(fangzi)
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
/usr/local/python3.6/bin/python3.6 /home/adapa/PycharmProjects/demo2/demo1.py
房子面积:126,房子户型:三室两厅,房子地址:朝阳区 长安街 666号,房子家具:[],房子剩余面积:126
家具名称:原木床,家具占地面积:4
房子面积:126,房子户型:三室两厅,房子地址:朝阳区 长安街 666号,房子家具:['原木床'],房子剩余面积:122
家具名称:沙发,家具占地面积:6
房子面积:126,房子户型:三室两厅,房子地址:朝阳区 长安街 666号,房子家具:['原木床', '沙发'],房子剩余面积:116
隐藏属性(保护对象的属性)
#!/usr/bin/env python
class dog:
def set_age(self,age):
if age >0 and age<=100:
self.age = age
def get_age(self):
return self.age
xiaobai = dog()
xiaobai.set_age(16)
print(xiaobai.get_age())
>>>>
/usr/local/python3.6/bin/python3.6 /home/adapa/PycharmProjects/demo2/demo02.py
16
私有属性
在Python中可以通过在属性变量名前加上双下划线定义属性为私有属性
#!/usr/bin/env python
class dog:
def __init__(self,name):
self.__name = name
def get_name(self):
return self.__name
xiaobai = dog('xiaobai')
print(xiaobai.get_name())
print(xiaobai.__name)
>>>>>>>>>>
/usr/local/python3.6/bin/python3.6 /home/adapa/PycharmProjects/demo2/demo02.py
xiaobai
Traceback (most recent call last):
File "/home/adapa/PycharmProjects/demo2/demo02.py", line 14, in <module>
print(xiaobai.__name)
AttributeError: 'dog' object has no attribute '__name'
Process finished with exit code 1
私有方法
#!/usr/bin/env python
class dog:
def __test2(self):
print('test2')
def test1(self):
print('test1')
def test3(self):
self.__test2()
xiaobai = dog()
xiaobai.test1()
xiaobai.test3()
>>>>>>>>>>>>>
/usr/local/python3.6/bin/python3.6 /home/adapa/PycharmProjects/demo2/demo02.py
test1
test2
Process finished with exit code 0
del方法
#!/usr/bin/env python
class dog:
def __test2(self):
print('test2')
def test1(self):
print('test1')
def test3(self):
self.__test2()
def __del__(self):
print('++++++++Over+++++++')
xiaobai = dog()
dabai = xiaobai
xiaobai.test1()
del xiaobai
dabai.test1()
>>>>>>>>>>>>>
/usr/local/python3.6/bin/python3.6 /home/adapa/PycharmProjects/demo2/demo02.py
test1
test1
++++++++Over+++++++
查看对象应用计数
继承
#!/usr/bin/env python
class Animal:
def eat(self):
print('eat')
def sellp(self):
print('sellp')
def drink(self):
print('drink')
def run(self):
print('run')
class dog(Animal):
def jiao(self):
print('汪汪叫')
class cat(Animal):
def zua(self):
print('抓老鼠')
xiaobai = dog()
xiaobai.run()
xiaohua =cat()
xiaohua.sellp()
>>>>>>>
/usr/local/python3.6/bin/python3.6 /home/adapa/PycharmProjects/demo2/demo02.py
run
sellp
Process finished with exit code 0
子类继承父类,父类的父类
#!/usr/bin/env python
class Animal:
def eat(self):
print('eat')
def sellp(self):
print('sellp')
def drink(self):
print('drink')
def run(self):
print('run')
class dog(Animal):
def jiao(self):
print('汪汪叫')
class xiaotianquan(dog):
def fie(self):
print('飞')
xiaotianquan = xiaotianquan()
xiaotianquan.fie()
xiaotianquan.jiao()
xiaotianquan.eat()
>>>>>>>>>>>>>>>>>
/usr/local/python3.6/bin/python3.6 /home/adapa/PycharmProjects/demo2/demo02.py
飞
汪汪叫
eat
Process finished with exit code 0
重写
#!/usr/bin/env python
class Animal:
def eat(self):
print('eat')
def sellp(self):
print('sellp')
def drink(self):
print('drink')
def run(self):
print('run')
class dog(Animal):
def jiao(self):
print('汪汪叫')
class xiaotianquan(dog):
def fie(self):
print('飞')
def jiao(self):
print('狂叫')
xiaotianquan = xiaotianquan()
xiaotianquan.fie()
xiaotianquan.jiao()
xiaotianquan.eat()
>>>>>
/usr/local/python3.6/bin/python3.6 /home/adapa/PycharmProjects/demo2/demo02.py
飞
狂叫
eat
Process finished with exit code 0
调用被重写的方法
#!/usr/bin/env python
class Animal:
def eat(self):
print('eat')
def sellp(self):
print('sellp')
def drink(self):
print('drink')
def run(self):
print('run')
class dog(Animal):
def jiao(self):
print('汪汪叫')
class xiaotianquan(dog):
def fie(self):
print('飞')
def jiao(self):
print('狂叫')
#第一种调用重写的父类方法
#dog.jiao(self)
#第二种
super().jiao()
xiaotianquan = xiaotianquan()
xiaotianquan.fie()
xiaotianquan.jiao()
xiaotianquan.eat()
>>>>
/usr/local/python3.6/bin/python3.6 /home/adapa/PycharmProjects/demo2/demo02.py
飞
狂叫
汪汪叫
eat
Process finished with exit code 0
私有方法,私有属性,在继承中的表现
#!/usr/bin/env python
class A:
def __init__(self):
self.name = 'MIMI'
self.__name = 'BIBI'
def test1(self):
print('test1')
def __test2(self):
print("___test2")
def get_MM(self):
print(self.__name)
self.__test2()
class b(A):
def get_mm(self):
print(self.__name)
self.__test2()
C = b()
C.get_MM()
C.get_mm()
>>>>>>>>>>>>
/usr/local/python3.6/bin/python3.6 /home/adapa/PycharmProjects/demo2/demo02.py
Traceback (most recent call last):
BIBI
___test2
File "/home/adapa/PycharmProjects/demo2/demo02.py", line 22, in <module>
C.get_mm()
File "/home/adapa/PycharmProjects/demo2/demo02.py", line 17, in get_mm
print(self.__name)
AttributeError: 'b' object has no attribute '_b__name'
Process finished with exit code 1
多继承
#!/usr/bin/env python
class test(object): #定义新样式类
def test1(self):
print("test1")
class test2(test):
def test2(self):
print("test2")
class test3(test):
def test3(self):
print("test3")
>>>>>>>>>>>>
/usr/local/python3.6/bin/python3.6 /home/adapa/PycharmProjects/demo2/demo02.py
testzeo
test3
test2
test1
Process finished with exit code 0
多继承注意点
多态
class dog(object):
def print_self(self):
print("汪汪汪大家好")
class xiaotianquan(dog):
def print_self(self):
print("汪!汪!汪!我是你们的老大哮天犬")
def js(MIMI):
MIMI.print_self()
s1 = dog()
js(s1)
s2 = xiaotianquan()
js(s2)
>>>>>>>>>>
/usr/local/python3.6/bin/python3.6 /home/adapa/PycharmProjects/demo2/demo03.py
汪汪汪大家好
汪!汪!汪!我是你们的老大哮天犬
Process finished with exit code 0
类属性和实例属性
class Tools(object):
mun = 0 #类属性
def __init__(self,new_name):#实例方法
self.new_name = new_name #实例属性
Tools.mun += 1 #调用类属性
name1 = Tools("name1")
name2 = Tools("name2")
name3 = Tools("name3")
print("Tools次数:%d"%Tools.mun)
>>>>>>>>>>>>>>>>>>
/usr/local/python3.6/bin/python3.6 /home/adapa/PycharmProjects/demo2/demo04.py
Tools次数:3
Process finished with exit code 0
实例方法,类方法,静态方法
#!/usr/bin/env python
class Game(object):
num = 0 #类属性
def __init__(self):#实类方法
self.name = 'Game'
@classmethod#类方法
def add_mun(cls):
cls.num = cls
@staticmethod#静态方法
def game():
print('_________kais Game_________')
Game1 = Game()
print(Game1.name)
# Game.add_mun() #用类名调用类方法
Game1.add_mun()#用实列名调用类方法
Game1.game()#用实列名调用静态方法
Game.game()#用类名调用静态方法
>>>>>>>>>>>>>>>>>>
/usr/local/python3.6/bin/python3.6 /home/adapa/PycharmProjects/demo2/demo04.py
Game
_________kais Game_________
_________kais Game_________
Process finished with exit code 0
练习题
设计一个类,一个卖车是4S店
#!/usr/bin/env python
class CatStore(object):
def __init__(self):
self.catleixing = CatLX()
def Predefined(self,cat_name):
return self.catleixing.neixing(cat_name)
class CatLX(object):
def neixing(self,name):
if name == 'redcat':
return redcat()
elif name == 'bullcat':
return bullcat()
elif name == 'ssCat':
return ssCat()
class Cat(object):
def didi(self):
print("滴滴响")
def run(self):
print("跑")
def storp(self):
print("刹车")
class redcat(Cat):
pass
class bullcat(Cat):
pass
class ssCat(Cat):
pass
catstore = CatStore()
mycar = catstore.Predefined('redcat')
mycar.didi()
>>>>>>>>>>
/usr/local/python3.6/bin/python3.6 /home/adapa/PycharmProjects/demo2/demo04.py
滴滴响
Process finished with exit code 0
工厂方法模式
基类完善大体框架,实现交给子类
new方法
#!/usr/bin/env python
class dog(object):
def __init__(self):
print("_______INIT________")
def __del__(self):
print("________del_____________")
def __new__(cls):
print("_______new_________")
return object.__new__(cls)
xiaotianquan = dog()
>>>>>>>>>>>
/usr/local/python3.6/bin/python3.6 /home/adapa/PycharmProjects/demo2/demo04.py
_______new_________
_______INIT________
________del_____________
Process finished with exit code 0
创建单列对象
#!/usr/bin/env python
class dog(object):
__jsq =None
def __new__(cls):
if cls.__jsq == None:
cls.__jsq = object.__new__(cls)
return cls.__jsq
else:
return cls.__jsq
one = dog()
print(id(one))
two = dog()
print(id(two))
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
/usr/local/python3.6/bin/python3.6 /home/adapa/PycharmProjects/demo2/demo04.py
140012579000840
140012579000840
Process finished with exit code 0
只初始化一次
#!/usr/bin/env python
class dog(object):
__jsq =None
__ok = True
def __new__(cls,*args, **kwargs):
if cls.__jsq == None:
cls.__jsq = object.__new__(cls)
return cls.__jsq
else:
return cls.__jsq
def __init__(self,name):
if dog.__ok == True:
self.name = name
dog.__ok = False
one = dog("one")
print(id(one))
print(one.name)
two = dog("two")
print(id(two))
print(one.name)
>>>>>>>>>>>>>>>>>>>>>>>>>>>
/usr/local/python3.6/bin/python3.6 /home/adapa/PycharmProjects/demo2/demo04.py
140137900655392
one
140137900655392
one
Process finished with exit code 0
异常
#!/usr/bin/env python
try:
open("dsds")
print("________运行正常1_____")
print(nameS)
print("________运行正常2_____")
except NameError:#异常名称
print("异常处理")#捕获异常后的处理方案
except FileNotFoundError:
print("FileNotFoundErrorNONO")
print("________运行正常3_____")
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
/usr/local/python3.6/bin/python3.6 /home/adapa/PycharmProjects/demo2/demo04.py
FileNotFoundErrorNONO
________运行正常3_____
Process finished with exit code 0
#!/usr/bin/env python
#coding=utf-8
try:
#11/0
#open("dsds")
print("________运行正常1_____")
#print(nameS)
print("________运行正常2_____")
except (NameError,FileNotFoundError):#异常名称
print("异常处理")#捕获异常后的处理方案
except Exception as bit:#如果上面没有捕获到异常,这个Exception(所有异常)就会捕获到异常
print("%s错误"%bit)
else:
print("没有异常才会执行这个")
finally:
print("不管有没有异常都有执行")
print("________运行正常3_____")
>>>>>>>>>>>>>>>>>>>>
/usr/local/python3.6/bin/python3.6 /home/adapa/PycharmProjects/demo2/demo04.py
________运行正常1_____
________运行正常2_____
没有异常才会执行这个
不管有没有异常都有执行
________运行正常3_____
Process finished with exit code 0
异常的传递
抛出自定义异常
#!/usr/bin/env python
#coding=utf-8
class input_length_is_not_enough(Exception):#自定义异常
def __init__(self,s,length):
self.len = len(s)
self.length = length
def main():
try:
s = input("please you input >>>")
if len(s)<3:
#raise调用你自定义的异常
raise input_length_is_not_enough(s,3)
except input_length_is_not_enough as result:
print("你输入的长度为:%d,最少输入长度为:%d"%(result.len,result.length))
else:
print("运行正常")
main()
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
/usr/local/python3.6/bin/python3.6 /home/adapa/PycharmProjects/demo2/demo04.py
please you input >>>2
你输入的长度为:1,最少输入长度为:3
Process finished with exit code 0
在异常处理中抛出异常
#!/usr/bin/env python
#coding=utf-8
class Test(object):
def __init__(self,a,b):
self.a = a
self.b = b
def yunshuan(self):
try:
cc = self.a / self.b
print(cc)
except Exception as reslut:
print("写入log日志%s"%reslut)
raise #调用系统原版的异常处理
go = Test(11,0)
go.yunshuan()
》》》》》》》》》》》》
/usr/local/python3.6/bin/python3.6 /home/adapa/PycharmProjects/demo2/demo04.py
写入log日志division by zero
Traceback (most recent call last):
File "/home/adapa/PycharmProjects/demo2/demo04.py", line 16, in <module>
go.yunshuan()
File "/home/adapa/PycharmProjects/demo2/demo04.py", line 10, in yunshuan
cc = self.a / self.b
ZeroDivisionError: division by zero
Process finished with exit code 1
补充
if 的各种真假判断
模块
def test1():
print("test1")
def test2():
print("test2")
if __name__ == "__main__":#判断执行者 测试用
test1()
test2()
# import demoMod05
# demoMod05.test1()
#demoMod05.test2()
# from demoMod05 import test1,test2
# test1()
# test2()
# from demoMod05 import *
# test1()
# test2()
import demoMod05 as M5 #取一个小名
M5.test2()
M5.test1()
>>>>>>>>>>>>>>>>>>>>>>>>>>>>
/usr/local/python3.6/bin/python3.6 /home/adapa/PycharmProjects/demo2/demo05.py
test2
test1
Process finished with exit code 0