Python inheritance code example

不言
Release: 2019-03-09 13:59:01
forward
2051 people have browsed it

This article brings you code examples about Python inheritance. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

#单继承
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)
Copy after login

#多继承
注意,当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()
Copy after login

The above is the detailed content of Python inheritance code example. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!