zoukankan      html  css  js  c++  java
  • python类与对象练习题扑克牌

    #定义一个扑克类,属性是颜色,数字。
    #定义一个手类,属性是扑克牌得颜色数字
    #定义一个人类,属性是左手,右手。类里定义一些方法,比如交换,展示

    class Poker :
       def __init__(self,colour ,num):
          self.colour = colour
          self.num = num
       def __str__(self):
          return "{},{}".format(self.colour,self.num)
    p1 = Poker("红桃","A")
    p2 = Poker("黑桃","k")
    #定义一个手得类
    class Hand :
       def __init__(self,poker):
          self.poker = poker
    left_hand = Hand(p1)
    right_hand = Hand(p2)
    #定义一个人的类
    class Person :
       def __init__(self,left_hand ,right_hand):
          self.left_hand = left_hand
          self.right_hand = right_hand
       def show_hand(self):
          print(self.right_hand.poker,self.left_hand.poker)
       def swap_hand(self):
          self.left_hand.poker,self.right_hand.poker = self.right_hand.poker,self.left_hand.poker
    xiaoming = Person(left_hand,right_hand)
    xiaoming.show_hand()
    xiaoming.swap_hand()
    xiaoming.show_hand()
    

      



    总结,里面的变量只是一个变量,形参是变量,对象也是变量。当你将一个对象作为一个参数传入另外一个类中的时候,才会发生关系。给大家一个改良版的,加强大家理解。
    class Poker :
       def __init__(self,colour ,num):
          self.colour = colour
          self.num = num
       def __str__(self):
          return "{},{}".format(self.colour,self.num)
    p1 = Poker("红桃","A")
    p2 = Poker("黑桃","k")
    #定义一个手得类
    class Hand :
       def __init__(self,pai):
          self.paipai = pai
    left_hand = Hand(p1)
    right_hand = Hand(p2)
    #定义一个人的类
    class Person :
       def __init__(self,bianliang ,suibian):
          self.zuoshou = bianliang
          self.youshou = suibian
       def show_hand(self):
          print(self.youshou.paipai,self.zuoshou.paipai)
       def swap_hand(self):
          self.zuoshou.paipai,self.youshou.paipai = self.youshou.paipai,self.zuoshou.paipai
    #xiamian de left_hand riaht_hand 是Hand的对象哦。
    xiaoming = Person(left_hand,right_hand)
    xiaoming.show_hand()
    xiaoming.swap_hand()
    xiaoming.show_hand()
    

      



    同学们仔细对比一下,仔细体会一下,就是说类的属性,原来是空白的,只有你给她传进去 一个具体的之后,它才实例化。传之前,类的属性函数_init_里面的参数,只是一个变量。



  • 相关阅读:
    Hadoop生态圈
    Kafka原理总结
    多线程 Threading Multiprocessing(Python)
    多线程
    MySQL 基础操作
    Python3+RobotFramework自动化测试九:用Python写Roboot Framework测试
    Python3+RobotFramework自动化测试八:关键字封装
    Python3+RobotFramework自动化测试七:SeleniumLibrary web测试-百度搜索和邮箱登录
    Python3+RobotFramework自动化测试六:Selenium API
    Python3+RobotFramework自动化测试五:元素定位
  • 原文地址:https://www.cnblogs.com/chaojiyingxiong/p/9240722.html
Copyright © 2011-2022 走看看