Python 类的继承和实例化

题目描述:

1、新建Animal类,具有height和color属性以及eat方法;
2、新建Dog类,继承于Animal类,具有name和age属性以及eat方法;
3、实例化Dog类。


一、分析题目

题目并不复杂,只有两个类分别有两个属性一个方法,最后把Dog子类实例化。

Animal int height string color eat() Dog string name int age eat()

二、代码实现

1、Animal类

Python中变量不需要声明就可以使用,所以Animal中的height和color不需要事先定义。

class Animal(object):
    def __init__(self,height,color):
        self.height=height
        self.color=color        
        print("身高:%dcm" % (self.height))  #格式化输出
        print("颜色:%s" % (self.color))
    def eat(self):
        print("吃东西")

注意:如果输出 print 使用的是如下格式

print("身高:" + self.height +"cm")

要注意参数的类型,比如,我们需要的 height 是 int 类型,但是如果把输出写成这种格式就会报错

TypeError: can only concatenate str (not "int") to str

①所以最好使用 格式化输出

②或者把这句话改为:

 print("身高:" + str(self.height) +"cm")

2、Dog类

Dog类继承自Animal类,而且比父类多了两个属性name和age,另外把父类的eat方法重写。

class Dog(Animal):
    def __init__(self,height,color,name,age):
        Animal.__init__(self,height,color)
        self.name=name
        self.age=age
        print("名字:%s" % (self.name))
        print("年龄:%d岁" % (self.age))
    def eat(self):
        print("狗吃骨头")

3、实例化

实例化Dog子类并查看输出结果。

if __name__ == "__main__":
    my_dog=Dog(55,"黑色","汪汪",2)
    my_dog.eat()

结果为:
Python 简单类的继承和实例化 代码运行结果

关于这里的第一句代码 if name == “main”: 如果这个Animal类和Dog类只在本次使用的话其实也可以不要,具体使用方法在下面链接中有详细介绍。
相关资料:Python中if name == ‘main’:的作用和原理.

猜你喜欢

转载自blog.csdn.net/zibery/article/details/121182284