Python 面向对象 构造、继承

构造方法 自动调用 前后两个横线 

#无参构造
class Myclass:   
    def __init__(self):
        self.data = 'a'
        print(self.data)

x = Myclass()

#带参构造
class area:   
    def __init__(self,height,weight):
        self.h = height
        self.w = weight
        print(self.h*self.w)

x = area(3.0,4.0)

继承 单继承 多继承

#继承
class People:
    name = ' '
    age = 0
    weight = 0
    
    def __init__(self,n,a,w):
        self.name = n
        self.age = a
        self.weight = w
    
    def show(self):
        print("My name is %s, %d years old, %d kg"%(self.name,self.age,self.weight))

#单继承
class Student(People):
    grade = ' '
    def __init__(self,n,a,w,g):
        People.__init__(self,n,a,w)
        self.grade = g
        
    def show(self):
        print("Name:%s  Age:%d  Weight:%d  Grade:%s"%(self.name,self.age,self.weight,self.grade))
        
    
class  Topic():
    topic = ' '
    def __init__(self,t):
        self.topic = t
    
    def show(self):
        print("Topic:%s"%self.topic)

#多继承
class Sample(Student,Topic):
    h = 0
    def __init__(self,h,n,a,w,g,t):
        self.height = h
        Student.__init__(self,n,a,w,g)
        Topic.__init__(self,t)
    def show(self):
        print("Name:%s  Height:%d  Topic:%s"%(self.name,self.height,self.topic))
    

        
p = People('May',21,49)
p.show()

s = Student('May',16,48,'senior high school')
s.show()

t = Sample(160,'May',18,49,'senior high school','Health')
t.show()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值