python 类的继承

先给出一个例子:

class People(): #定义类,要大写,python 2中要在括号里加如object这个单词

    def __init__(self,n,a,w):   #定义一个方法(类下的函数都称为方法),初始化形参(属性)
        self.name = n
        self.age = a
        self.weight = w

    def express(self):   #定义第二个函数,括号里面的self不可少,表示需要用到初始化里的形参
        print('My name is %s, and my age is %d' %(self.name,self.age))

class Xiaowen(People):   #定义另一个类,并继承People父类

    def __init__(self,n,a,w,g): #在父类上加了一个形参g
        People.__init__(self,n,a,w)   #调用父类的构造函数,用于将父类和子类联系起来
        self.grade = g  

    def express(self):
        print('My name is %s, and my grade is %d'%(self.name,self.grade))


people = Xiaowen('wudl',22,53,3)  #实例
people.express()

猜你喜欢

转载自blog.csdn.net/mr_cat123/article/details/80491862
今日推荐