This article mainly introduces the inheritance code examples of classes in Python. This article provides the code and running effect directly. if you need it, you can refer to the inheritance compiling of C ++. Python is more concise, and the efficiency is very high. Below is a simple Python inheritance example.
The code is as follows:
#! /Usr/bin/python
# Filename: pyclass. py
Class Member:
Def _ init _ (self, name, age ):
Self. name = name
Self. age = age
Print 'Member init: % s' % self. name
Def tell (self ):
Print 'name: % s, Age: % d' % (self. Name, self. age ),
Class Student (Member ):
Def _ init _ (self, name, age, marks ):
Member. _ init _ (self, name, age)
Self. marks = marks
Print 'student init: % s' % self. name
Def tell (self ):
Member. tell (self)
Print 'marks: % d' % self. Marks
Class Teacher (Member ):
Def _ init _ (self, name, age, salary ):
Member. _ init _ (self, name, age)
Self. salary = salary
Print 'teacher init: % s' % self. name
Def tell (self ):
Member. tell (self)
Print 'salary: % d' % self. Salary
S = Student ('Tom ', 20, 80)
T = Teacher ('Mrs. Huang ', 30,500 00)
Members = [s, t]
For mem in members:
Mem. tell ()
Running effect:
The code is as follows:
[Root @ localhost hhl] # python pyclass. py
Member init: Tom
Student init: Tom
Member init: Mrs. Huang
Teacher init: Mrs. Huang
Name: Tom, Age: 20 Marks: 80
Name: Mrs. Huang, Age: 30 Salary: 50000
We also write C ++ examples with the same effect:
The code is as follows:
// Filename: class. cpp
# Include
# Include
Using namespace std;
Class Member
{
Public:
Member (char * n, int );
Void tell ();
Private:
Char name [10];
Int age;
};
Member: Member (char * n, int)
{
Memcpy (name, n, sizeof (name ));
Age =;
Cout <"Member init:" < }
Void Member: tell ()
{
Cout <"Name:" <
Class Student: public Member
{
Public:
Student (char * n, int a, int m );
Void tell_s ();
Private:
Int marks;
};
Student: Student (char * n, int a, int m): Member (n,)
{
Marks = m;
Cout <"Student init:" < }
Void Student: tell_s ()
{
Member: tell ();
Cout <"Marks:" < }
Class Teacher: public Member
{
Public:
Teacher (char * n, int a, int s );
Void tell_t ();
Private:
Int salary;
};
Teacher: Teacher (char * n, int a, int s): Member (n,)
{
Salary = s;
Cout <"Teacher init:" < }
Void Teacher: tell_t ()
{
Member: tell ();
Cout <"Salary:" < }
Int main (void)
{
Student s ("Tom", 20, 80 );
Teacher t ("Mrs. Huang", 30,500 00 );
S. tell_s ();
T. tell_t ();
Return 0;
}
Running effect:
The code is as follows:
[Root @ localhost hhl] #./class
Member init: Tom
Student init: Tom
Member init: Mrs. Huang
Teacher init: Mrs. Huang
Name: Tom, Age: 20, Marks: 80
Name: Mrs. Huang, Age: 30, Salary: 50000
The two have the same running effect, but python is more concise...