面向对象编程
1、步骤
1)OOA面向对象分析
2)OOD面向对象设计
3)OOP面向对象编程
2、实现
1)分析对象特征和行为
2)写类对象模板
3)实例化
举例
class Book:
count=0; #属于类,但不属于实例化对象的特征或方法
def __init__(self, title, price=0.0, author=None): # 构造函数,初始化时执行
self.title = title
self.price = price
self.author = author
Book.count +=1
def __del__(self): #删除对象时执行
Book.count -= 1
def __str__(self):
return self.title
def __repr__(self):
return '图书:{}'.format(self.title)
def cls_method(cls):
print('类函数')
def static_method():
print('静态函数,与实例无关')
if __name__ == '__main__':
book1 = Book('Python 入门', 69.9, 'eason')
# Book.count += 1
book2 = Book('NUAP',88,'James')
# Book.count +=1
print(book1.title)
print(Book.count)
del(book2)
print(Book.count)
Book.cls_method(book1)
Book.static_method()
Python 入门
2
1
类函数
静态函数,与实例无关
import datetime
class Book:
def __init__(self, title, price=0.0, author=None): # 构造函数,初始化时执行
self.title = title
self.price = price
self.author = author
@property #装饰器
def time(self):
return datetime.date.today()
@time.setter
def time(self,value):
raise AttributeError('禁止赋值时间')
@time.deleter
def time(self):
raise AttributeError('禁止删除时间')
if __name__ == '__main__':
book1 = Book('AUPE',99.9,'eason')
print(book1.time)
# book1.time=88
del(book1.time)
2019-08-15
Traceback (most recent call last):
File "E:/PycharmProjects/day04/main.py", line 103, in <module>
del(book1.time)
File "E:/PycharmProjects/day04/main.py", line 97, in time
raise AttributeError('禁止删除时间')
AttributeError: 禁止删除时间
3、特征
1)封装
根据 职责 将 属性 和 方法 封装 到一个抽象的 类 中
2)继承
实现代码的重用,相同的代码不需要重复的编写
class Student:
def __init__(self,name,age,score):
self.name = name
self.age = age
self.score = score
def status(self):
print('{} is studying!'.format(self.name))
def raise_score(self,percent):
self.score *= (1+percent)
class Stu(Student):
def __init__(self, name,age,score,hobby, father):
# super().__init__(name,age,score)
Student.__init__(self,name,age,score)
self.hobby = hobby
self.father = father
def status(self):
print('{} is playing!'.format(self.name))
if __name__ == '__main__':
stu1 = Stu('eason',22,60,'badminton','kobe')
print(stu1.name)
print(stu1.score)
stu1.raise_score(0.2)
print(stu1.score)```
```python
eason
60
72.0
3)多态
不同的 子类对象 调用相同的 父类方法,产生不同的执行结果
本引用连接:https://blog.youkuaiyun.com/weixin_43226484/article/details/83315216
#多态:
#多态的意思是,不同的对象,都实现了同一个接口,
#因此我们可以不管这个对象是什么,直接调用这个方法就可以了。
class Hero(object):
"""docstring for Hero"""
def __init__(self):
pass
def stroke(self):
pass
class Chengyaojin(Hero):
def stroke(self):
print(u'程咬金的回血大招')
class Xiangyu(Hero):
def stroke(self):
print('项羽的推人大招')
value = input('请选择英雄:')
hero = None
if value == '1':
hero = Chengyaojin()
else:
hero = Xiangyu()
hero.stroke()