python面向对象简单示例—小明手里的牌

xiaoxiao2022-06-11  17

小明手里有两张牌,左右♥K,右手♠A,小明交换两手的牌后,手里分别是什么?

本篇适合刚学习面向对象的新手,开拓思路。

思路: 先找到对象:左手、右手、♥K、♠A、小明根据对象抽象出对应的类:人、手、牌根据需要写出相应的逻辑,很可能反过来完善类的设计按照题目要求创建相关对象,调用相关方法,实现相关功能

分析:

对象: 小明、左手、右手、牌1、牌2            类:  人、手、牌

#, 扑克牌 class Poker: def __init__(self,color,number): self.color=color self.number=number def __str__(self): return '{}{}'.format(self.color,self.number) # 创建两张牌 p1=Poker('♥','k') p2=Poker('♠','A') # 手的类 class Hand: def __init__(self,poker): self.poker=poker def hold_poker(self,poker): self.poker=poker # 创建左右两只手 left_hand=Hand(p1) right_hand=Hand(p2) # 人的类 class Person: def __init__(self,name,left_hand,right_hand): self.name=name self.left_hand=left_hand self.right_hand=right_hand # 显示手里的牌 def show(self): print('{}张开手'.format(self.name),end=',') print('左手:{}'.format(self.left_hand.poker),end=',') print('右手:{}'.format(self.right_hand.poker)) # 交换手里的牌 def swap(self): self.left_hand.poker,self.right_hand.poker=self.right_hand.poker,self.left_hand.poker print('{}交换两手的牌'.format(self.name)) # 创建对象小明 xiaoming=Person('小明',left_hand,right_hand) # 展示手里的牌 xiaoming.show() # 交换两手的牌, xiaoming.swap() # 再展示手里的牌 xiaoming.show()

执行代码后,右键run运行结果:

小明张开手,左手:♥k,右手:♠A 小明交换两手的牌 小明张开手,左手:♠A,右手:♥k

 

转载请注明原文地址: https://www.6miu.com/read-4931157.html

最新回复(0)