Python继承的代码示例


本文摘自php中文网,作者不言,侵删。

本篇文章给大家带来的内容是关于Python继承的代码示例,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

#单继承

class Person(object):

    def __init__(self,name,age,height,weight):

        self.name = name

        self.age = age

        self.height = height

        self.weight = weight

    def eat(self):

        print("eating")

    def walk(self):

        print("walking")

    def __str__(self):

        return "name:%s,age:%d"%(self.name,self.age)

 

from person import Person

class Student(Person):

    def __init__(self,name,age,height,weight):

        #调用父类中的属性

        super(Student,self).__init__(name,age,height,weight)

    def studey(self):

        print("studying")

 

from student import Student

stu = Student("tom",25,252,63)

print(stu.name)


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

#多继承

注意,当self.money = money编程私有属性时,即self.__money会出现报错现象

,说明私有属性不能直接继承

 

class Father(object):

    def __init__(self,money):

        self.money = money

    def eat (self):

        print("eating")

     

class Mother(object):

    def __init__(self,facevalue):

        self.facevalue = facevalue

    def sleep(self):

        print("slepping")

        

from father import Father

from mother import Mother

class Child(Father,Mother):

    def __init__(self,money,facevalue):

        Father.__init__(self,money)

        Mother.__init__(self,facevalue)

    def study(self):

        print("studing")

     

 from child import Child

def main():

    ch = Child(5,"NICE")

    print(ch.money,ch.facevalue)

if __name__=='__main__':

    main()

以上就是Python继承的代码示例的详细内容,更多文章请关注木庄网络博客!!

相关阅读 >>

Python 讲解进制转换 int、bin、oct、hex

Python中的xlsxwriter库简单分析

Python中的lambda是什么意思

Python基于win32ui模块创建弹出式菜单

Python字典支持双向索引吗

新手学Python用什么书

Python操作excel文件的案例

Python防止sql注入方法介绍

Python中if语句的基本格式

Python中列表,元组 ,集合 ,字典之间的区别

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...