Discuss / Python / 练习练习~

练习练习~

Topic source
# -*- coding=utf-8 -*-

class People:

    def __init__(self,name,age,grade):
        self.name = name
        self.age = age
        self.grade = grade

    def print_data(self):
        print("我叫 %s ,今年 %d 岁了,上 %d 年级" % (self.name,self.age,self.grade))

class Student(People):

    def __init__(self,name,age,grade,like):
        People.__init__(self,name,age,grade)
        self.like = like

    def print_data(self):
        print("我叫 %s ,今年 %d 岁了,上 %d 年级,我喜欢 %s" % (self.name,self.age,self.grade,self.like))



class Tolal():

    def __init__(self,name,say):
        self.name = name
        self.say = say

    def print_data(self):
        print("我叫 %s 今天我为大家演讲的是 %s" % (self.name,self.say))

class Sample(Tolal,Student):

    def __init__(self,name,age,grade,like,say):
        Student.__init__(self,name,age,grade,like)
        Tolal.__init__(self,name,say)


s = People("Jack",12,5)
s.print_data()

x = Student("Jack",12,5,"Python")
x.print_data()

a = Sample("JAck",12,5,"Python","Python")
a.print_data()

但是,如果改成私有属性,就全部报错了~~~

按照你的例子编写的程序,为啥,是这样显示的呢?(代码都一样,所以有些地方就不复制了)

class Sample(Total, Student, People): def init(self, name, age, grade, like, say): Total.init(self, name, say) Student.init(self, name, age, grade, like)

a = Sample("Jack", 12, 5, "Python", "JAVA+Python") a.print_date()

为啥执行的结果是这样的呢?? My name is Jack,12 years old in 5 grade,I like Python

我已经把People的父类继承给了Student 最后的Sample,因为Student已经继承了People 所以class Sample就不用加People, 直接

class Sample(Total,Student):

然后,你把Tolat 和 Student的位置互换一下

Class Sample(Student,Total):

再执行一下结果 如果要把People加上Sample的话,Student就不要继承People了~~

  • 方法名同,默认调用的是在括号中排前地父类的方法

  • 1

Reply