python 继承:重写、拓展(六)

1.继承:父类有的子类也有

2.多继承:若继承多个父类有相同的函数,则继承前面的函数,传递参数的个数也与继承的函数位置有关

3.超继承:针对继承一个父类使用,不仅有父类的特写同时也有自己的新特性  super(类名,self).属性/方法名(参数)

4.重写:子类的函数名与父类的一致,就会重写函数override 覆盖,调用函数的时候只调用子类自己的函数,不在调用父类的,父类不能调用子类的函数,属性。

5.拓展:父类没有的函数,子类有。

class Dad:  #父类

    def __init__(self,name,age):

        self.name=name

        self.age=age

    def sport(self,hours):

        print("只喜欢游泳,每天游泳{0}小时".format(hours))

    def cooking(self):

        print("只会做蛋炒饭")

    def smoke(self):

        print("喜欢吸烟")

class Son(Dad):  #子类继承父类

    def sport(self,hours,*args):       #重写

        super(Son,self).sport(hours)  #保持父类的特性

        sport_name=''

        for item in args:

            sport_name+=item

            sport_name+=''

        print("我喜欢{0}这些运动。".format(sport_name))

    def coding(self,language="python"):  #拓展

        print("我是一个程序员,名字{0},今年{1},喜欢{2}编码".format(self.name,self.age,language))

son_1=Son("牛牛",8) #实例化

son_1.sport(2,"篮球","足球","排球")

son_1.coding()

例子:猜拳游戏

import random

class GussingGame:

    def choose_role(self):

        role={"1":"曹操","2":"张飞","3":"刘备"}

        input_role=input("请选择角色:1:曹操 2:张飞 3:刘备")

        return role[input_role]

    def human_fist(self):

        input_num=input("请出拳:1 石头 2 剪刀 3 ")

        return int(input_num)

    def machine_fist(self):

        input_num=random.randint(1,3)

        return input_num

    def human_vs_machine(self):

        human_win=0

        machine_win=0

        ping=0

        fist_num={"1":"石头","2":"剪刀","3":""}

        #选择角色

        role=self.choose_role()

        while True:

            #出拳

            human_fist=self.human_fist()

            #电脑出拳

            machine_fist=self.machine_fist()

            result=human_fist-machine_fist

            print(role+"出拳:{0}".format(fist_num[str(human_fist)]))

            print("电脑出拳:{0}".format(fist_num[str(machine_fist)]))

            if result==-1 or result==2:

                print("恭喜你,赢了!")

                human_win+=1

            elif result==-2 or result==1:

                print("很遗憾,你输了!")

                machine_win+=1

            else:

                print("平局!")

                ping+=1

            choice=input("是否还有继续输入【y】继续,输入【n】结束!")

            if choice=='y':

                continue

            elif choice=='n':

                print("游戏结束!")

                print("本次比赛{0},你赢{1},电脑赢{2},平局{3}".format(human_win+machine_win+ping,human_win,machine_win,ping))

                break

if __name__ == '__main__':

    gg=GussingGame()

    gg.human_vs_machine()

posted @ 2019-10-18 14:04  Y、  阅读(518)  评论(0编辑  收藏  举报