头歌educoder-Python程序设计-第五阶段 类与对象-类的继承

  关卡一:初识继承

import animalstest
# 请在下面填入定义fish类的代码,fish类继承自animals类
########## Begin ##########
class fish(animalstest.animals):
########## End ##########
    def __init__(self,name):
        self.name = name
    def swim(self):
        print("%s会游泳" %self.name)

# 请在下面填入定义leopard类的代码,leopard类继承自animals类
########## Begin ##########
class leopard(animalstest.animals):
########## End ##########
    def __init__(self,name):
        self.name = name
    def climb(self):
        print("%s会爬树" %self.name)

fName = input()
lName = input()
f = fish(fName)
f.breath()
f.swim()
f.foraging()
l = leopard(lName)
l.breath()
l.run()
l.foraging()


关卡二:覆盖方法

class Point:
    def __init__(self,x,y,z,h):
        self.x = x
        self.y = y
        self.z = z
        self.h = h
    def getPoint(self):
        return self.x,self.y,self.z,self.h
class Line(Point):
    # 请在下面填入覆盖父类getPoint()方法的代码,并在这个方法中分别得出x - y与z - h结果的绝对值
    ########## Begin ##########
    def getPoint(self):
        length_one = abs(self.x - self.y)
        length_two = abs(self.z - self.h)


    ########## End ##########
        print(length_one,length_two)
    

关卡三:从标准类派生

class ChangeAbs(int):
    def __new__(cls, val):
        # 填入使用super()内建函数去捕获对应父类以调用它的__new__()方法来计算输入数值的绝对值的代码
        # 求一个数的绝对值的函数为abs()
        # 返回最后的结果
        ########## Begin ##########
        return int.__new__(cls, abs(val))
        ########## End ##########

class SortedKeyDict(dict):
    def keys(self):
        # 填入使用super()内建函数去捕获对应父类使输入字典自动排序的代码
        # 返回最后的结果
        ########## Begin ##########
        return sorted(super(SortedKeyDict, self).keys())
        ########## End ##########



关卡四:多重继承

class A(object):
    def test(self):
        print("this is A.test()")
class B(object):
    def test(self):
        print("this is B.test()")
    def check(self):
        print("this is B.check()")
# 请在下面填入定义类C的代码
########## Begin ##########
class C(A,B):
########## End ##########
    pass
# 请在下面填入定义类D的代码
########## Begin ##########
class D(A,B):
########## End ##########
    def check(self):
        print("this is D.check()")
class E(C,D):
    pass




猜你喜欢

转载自blog.csdn.net/long_0901/article/details/121869706