当前位置:Gxlcms > Python > Python继承的代码示例

Python继承的代码示例

时间:2021-07-01 10:21:17 帮助过:89人阅读

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

  1. #单继承
  2. class Person(object):
  3. def __init__(self,name,age,height,weight):
  4. self.name = name
  5. self.age = age
  6. self.height = height
  7. self.weight = weight
  8. def eat(self):
  9. print("eating")
  10. def walk(self):
  11. print("walking")
  12. def __str__(self):
  13. return "name:%s,age:%d"%(self.name,self.age)
  14. from person import Person
  15. class Student(Person):
  16. def __init__(self,name,age,height,weight):
  17. #调用父类中的属性
  18. super(Student,self).__init__(name,age,height,weight)
  19. def studey(self):
  20. print("studying")
  21. from student import Student
  22. stu = Student("tom",25,252,63)
  23. print(stu.name)

  1. #多继承
  2. 注意,当self.money = money编程私有属性时,即self.__money会出现报错现象
  3. ,说明私有属性不能直接继承
  4. class Father(object):
  5. def __init__(self,money):
  6. self.money = money
  7. def eat (self):
  8. print("eating")
  9. class Mother(object):
  10. def __init__(self,facevalue):
  11. self.facevalue = facevalue
  12. def sleep(self):
  13. print("slepping")
  14. from father import Father
  15. from mother import Mother
  16. class Child(Father,Mother):
  17. def __init__(self,money,facevalue):
  18. Father.__init__(self,money)
  19. Mother.__init__(self,facevalue)
  20. def study(self):
  21. print("studing")
  22. from child import Child
  23. def main():
  24. ch = Child(5,"NICE")
  25. print(ch.money,ch.facevalue)
  26. if __name__=='__main__':
  27. main()

以上就是Python继承的代码示例的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行