目录
property–装饰器
通过包装getter(访问器)、setter(修改器)方法,来访问属性,主要是对属性进行操作
_属性名,暗示收到保护
- property–保镖(一对一),setter、getter方法–中间人(线人),最终目标:_属性名
- property(保镖)装饰setter、getter(线人),操作_属性名(最终目标)
__slots__魔法
因为python 是一门动态语言,我们可以对视给对象绑定新的属性或方法,因此,为了限定某些对象只能绑定某种属性,所以出现__slots__
注意:__slots__只限定对当前类的对象生效,对子类并不起任何作用,只管一代
静态方法、类方法
静态方法 @staticmethod
用检验前提条件,比如三角形的存在:两边之和大于第三边,也就是满足大前提,之后根据特有的特性来进行讨论
类方法@classmethod 第一个参数:cls
代表当前类相关信息的对象,通过第一个参数cls可以获取信息
多用多体会
两种方法都是:通过给类发消息来调用的
类之间的关系
三种关系:is-a、has-a、use-a 继承、关联、依赖
例如:
- 继承:学生和人,手机和电子产品,玫瑰和花
- 关联:汽车和引擎,电影和电影院
- 依赖:类其中的方法中的参数被别的类使用,司机有一个驾驶的行为(方法),其中(的参数)使用到了汽车,那么司机和汽车的关系就是依赖关系
继承、多态
继承、父类,子类、重写、多态
综合案例
1.奥特曼打小怪兽
2.扑克游戏
3.工资结算系统
1.
#奥特曼打小怪兽
from abc import ABCMeta, abstractmethod
from random import randint, randrange
class Fighter(object, metaclass=ABCMeta):
#战斗者
__slots__ = ('_name', '_hp')
def __init__(self, name, hp):
self._name = name
self._hp = hp #hp生命值
@property
def name(self):
return self._name
@property
def hp(self):
return self._hp
@hp.setter
def hp(self, hp):
self._hp = hp if hp>=0 else 0
@property
def alive(self):
return self._hp > 0
@abstractmethod
def attack(self, other):
#other是被攻击的对象
pass
class Ultraman(Fighter):
__slots__ = ('_name', '_hp', '_mp')
def __init__(self, name, hp, mp):
#hp--生命值
#mp--魔法值
super().__init__(name, hp)
self._mp = mp
def attack(self, other):
other.hp -= randint(15,25)
def huge_attack(self, other):
#终究必杀技
if self._mp >= 50:
self._mp -= 50
injury = other.hp * 3 // 4
injury = injury if injury > 50 else 50
other.hp -= injury
return True
else:
self.attack(other)
return False
def magic_attack(self, other):
if self._mp >= 20:
self._mp -= 20
for temp in other:
if temp.alive :
temp.hp -= randint(10,15)
return True
else:
return False
def resume(self):
incr_point = randint(1,10)
self._mp += incr_point
return incr_point
def __str__(self):
return '~~~%s奥特曼~~~\n' % self._name +\
'生命值:%d\n' % self._hp + \
'魔法值:%d\n' % self._mp
class Monster(Fighter):
__slots__ = ('_name', '_hp')
def attack(self, other):
other.hp -= randint(10,20)
def __str__(self):
return '~~~%s小怪兽~~~' % self._name + \
'生命值:%d' % self._hp
def is_any_alive(monsters):
for monster in monsters:
if monster.alive > 0 :
return True
return False
def select_alive_one(monsters):
monsters_len = len(monsters)
while True:
index = randrange(monsters_len)
monster = monsters[index]
if monster.alive > 0:
return monster
def display_info(ultraman, monsters):
print(ultraman)
for monster in monsters:
print(monster, end='')
def main():
u = Ultraman('A', 1000, 20)
m1 = Monster('a', 250)
m2 = Monster('b', 200)
m3 = Monster('c', 100)
ms = [m1,m2,m3]
fighter_round = 1
while u.alive and is_any_alive(ms):
print('========第%02d回合=======' % fighter_round)
m = select_alive_one(ms)
skill = randint(1,10)
if skill <= 6:
print('%s使用普通攻击打了%s.' % (u.name, m.name))
u.attack(m)
print('%s的魔法值恢复了%d点' % (u.name, u.resume()))
elif skill <= 9:
if u.magic_attack(ms):
print('%s的魔法值恢复了%d点。' % (u.name, u.resume()))
else:
print('%s使用魔法失败。' % u.name)
else:
if u.huge_attack(m):
print('%s使用终极必杀技虐了%s' % (u.name, m.name))
else:
print('%s使用普通攻击打了%s' % (u.name, m.name))
print('%s的魔法值恢复了%d点' % (u.name, u.resume()))
if m.alive > 0:
print('%s回击了%s' % (m.name, u.name))
m.attack(u)
display_info(u, ms)
fighter_round += 1
print('\n=======战斗结束========\n')
if u.alive > 0:
print('%s奥特曼胜利!' % u.name)
else:
print('小怪兽胜利!')
if __name__ == '__main__':
main()
2.
import random
class Card(object):
def __init__(self, suite, face):
self._suite = suite
self._face = face
@property
def face(self):
return self._face
@property
def suite(self):
return self._suite
def __str__(self):
if self._face == 1:
face_str = 'A'
elif self._face == 11:
face_str = 'J'
elif self._face == 12:
face_str = 'Q'
elif self._face == 13:
face_str = 'K'
else:
face_str = str(self._face)
return '%s%s' % (self._suite, face_str)
def __repr__(self):
return self.__str__()
class Poker(object):
def __init__(self):
self._cards = [Card(suite, face)
for suite in '♠♥♣♦'
for face in range(1,14)]
self._current = 0
@property
def cards(self):
return self._cards
def shuffle(self):
self._current = 0
random.shuffle(self._cards)
@property
def next(self):
#洗牌,随机乱序
card = self._cards[self._current]
self._current += 1
return card
@property
def has_next(self):
return self._current < len(self._cards)
class Player(object):
def __init__(self, name):
self._name = name
self._cards_on_hand = []
@property
def name(self):
return self._name
@property
def cards_on_hand(self):
return self._cards_on_hand
def get(self, card):
self._cards_on_hand.append(card)
def arrange(self, card_key):
self._cards_on_hand.sort(key = card_key)
def get_key(card):
return (card.suite, card.face)
def main():
p = Poker()
p.shuffle()
players = [Player('东邪'), Player('西毒'), Player('南帝'), Player('北丐')]
for _ in range(13):
for player in players:
player.get(p.next)
for player in players:
print(player.name + ':', end=' ')
player.arrange(get_key)
print(player.cards_on_hand)
if __name__ == '__main__':
main()
3.
from abc import ABCMeta, abstractmethod
class Employee(object, metaclass = ABCMeta):
def __init__(self, name):
self._name = name
@property
def name(self):
return self._name
@abstractmethod
def get_salary(self):
"""获得月薪
return: 月薪
"""
pass
class Manager(Employee):
def get_salary(self):
return 15000.0
class Progammer(Employee):
def __init__(self, name, working_hour=0):
super().__init__(name)
self._working_hour = working_hour
@property
def working_hour(self):
return self._working_hour
@working_hour.setter
def working_hour(self, working_hour):
self._working_hour = working_hour if working_hour > 0 else 0
def get_salary(self):
return 150.0*self._working_hour
class Saleman(Employee):
def __init__(self, name, sales=0):
super().__init__(name)
self._sales = sales
@property
def sales(self):
return self._sales
@sales.setter
def sales(self, sales):
self._sales = sales if sales > 0 else 0
def get_salary(self):
return 1200.0 + self._sales * 0.05
def main():
emps = [
Manager('刘备'),Progammer('诸葛亮'),Saleman('赵云'),
Manager('孙权'),Progammer('周瑜'),Saleman('鲁肃'),
Manager('曹操'),Progammer('荀彧'),Saleman('司马懿')]
for emp in emps:
if isinstance(emp, Progammer):
emp.working_hour = int(input('请输入%s的工作时间:' % emp.name))
elif isinstance(emp, Saleman):
emp.sales = float(input('请输入%s的销售额:' % emp.name))
print('%s本月工资为:¥%s元' % (emp.name, emp.get_salary()))
if __name__ == '__main__':
main()