您的位置:首页 > 编程语言 > Python开发

Python10--面向对象

2017-11-20 22:12 232 查看
面向过程:根据业务逻辑从上到下写代码
面向对象:将数据与函数绑定到一起,进行封装,这样可以更快的开发程序,减少重复代码的重写过程

类:具有相同属性和行为失误的统称
对象:具体事物的存在

类的构成:

名称:类名
属性:数据
方法:进行操作的方法(行为)

全局变量----函数
属性----方法

  1
#类名
  2 class
Cat:
  3
#属性
  4

  5
   
#init 初始化,前后两个下划线
  6
   
def
__init__(self,newName,newAge):
  7
       
print('---我是一只小猫咪---')
  8
       
self.name = newName
  9
        self.age = newAge
 10

 11

 12
#方法(类里面的方法毕竟不是函数,不能等同于函数理解)
 13
   
def
eat(self):
 14
       
print('猫在吃鱼')
 15

 16
   
def
drink(self):
 17
       
print('猫在喝水')
 18

 19
   
def
introduce(self):
 20
       
print('%s的年龄是%d'%(self.name,self.age))
 21

 22
#创建对象
 23
tom = Cat('汤姆',20)
 24

 25
#调用tom指向的对象中的方法
 26
tom.eat()
 27
tom.drink()
 28

 29
#给tom指向的对象添加2个属性
 30
tom.name =
'汤姆'
 31
tom.age =
20
 32

 33
print('%s的年龄是%d'%(tom.name,tom.age))
 34

 35
lanmao = Cat('蓝猫',10)
 36
lanmao.name =
'蓝猫'
 37
lanmao.age =
10
 38
lanmao.introduce()

  1 class
Cat:
  2
#属性
  3

  4
   
#init 初始化,前后两个下划线
  5
   
def
__init__(self,newName,newAge):
  6
       
print('---我是一只小猫咪---')
  7
       
self.name = newName
  8
        self.age = newAge
  9
       
print('%s的年龄:%d'%(self.name,self.age))
 10
   
# 必定运行,不加__str__ 方法会输出对象的地址
 11
   
def
__str__(self):
 12
       
return
'%s的年龄:%d'%(self.name,self.age)
 13

 14
   
def
introduce(self):
 15
       
print('%s的年龄是%d'%(self.name,self.age))
 16

 17
#创建对象
 18
tom = Cat('汤姆',20)
 19

 20
lanmao = Cat('蓝猫',10)
 21

 22
print(tom)
 23
print(lanmao)

  1 class
SweetPotato:
  2
   
def
__init__(self):
  3
        self.cookedString =
'生的'
  4
        self.cookedTime =
0
  5
        self.condiments = []
  6

  7
   
def
__str__(self):
  8
       
return
'地瓜%s,考了%d分钟,加了%s'%(self.cookedString,self.cookedTime,st
d6de
r(self.condiments))
  9

 10
   
def
cook(self,cookedTime):
 11

 12
        self.cookedTime += cookedTime
 13

 14
       
if cookedTime >=0
and cookedTime <3:
 15
            self.cookedString =
'生的'
 16
       
elif cookedTime >=3
and cookedTime <5:
 17
            self.cookedString =
'半生不熟'
 18
       
elif cookedTime >=5
and cookedTime <8:
 19
            self.cookedString =
'熟了'
 20
       
else :
 21
            self.cookedString =
'糊了'
 22

 23
   
def
addCondiments(self,itrm):
 24
        self.condiments.append(itrm)
 25

 26
#创建一个对象
 27
diGua = SweetPotato();
 28

 29
diGua.cook(1)
 30
diGua.addCondiments('盐')
 31
print(diGua)
 32
diGua.cook(3)
 33
diGua.addCondiments('糖')
 34
print(diGua)
 35
diGua.cook(5)
 36
diGua.addCondiments('味精')
 37
print(diGua)
 38
diGua.cook(7)
 39
diGua.addCondiments('酱油')
 40
print(diGua)
 41
diGua.cook(9)
 42
print(diGua)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 面向对象