python初级(302) 6 对象(四)

一、复习

1、什么是多态

2、复习上一节课内容

class Triangle:
    """
    三角形类
    """
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def get_area(self):
        area = self.width * self.height / 2.0
        return area


class Square:
    """
    正方形类
    """
    def __init__(self, size):
        self.size = size

    def get_area(self):
        area = self.size * self.size
        return area


t1 = Triangle(3, 5)
print(t1.get_area())

s1 = Square(3)
print(s1.get_area())

二、继承:向父母学习

在面向对象编程中,类可以从其他类继承属性和方法。这样就有了类的整个家族,这个家族中的每个类共享相同的属性和方法。这样一来,每次向家族增加新成员时就不必从头开始。

从其他类继承属性或方法的类称为派生类或子类。被继承的叫做父类。

class People:
    def __init__(self, name):
        self.name = name

    def talk(self):
        print("My name is {}".format(self.name))


people = People("XiaoWang")
people.talk()


class Student(People):
    pass


student = Student("XiaoWang")
student.talk()

st1 = Student("XiaoWang")
st1.talk()

代码桩的概念:

pass

三、课后练习:

一个Animal类, 有两个属性,名字name和年龄age

一个方法,talk(), 假如这个动物是猫,并且3岁了,打印出

"My Name is cat,3 years old"

由父类Animal派生出Cat类和Dog类,并生成对应的对象

原文地址:https://www.cnblogs.com/luhouxiang/p/11876652.html