相对于c++的继承编写,python更简洁,而且效率也是很高的,下面编写一个简单python的继承例子。
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, 50000)
members = [s, t]
for mem in members:
mem.tell()
运行效果:
[root@localhost hhl]
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
我们同样编写同样效果的c++例子:
#include
#include
using namespace std;
class member
{
public:
member(char *n, int a);
void tell();
private:
char name[10];
int age;
};
member::member(char *n, int a)
{
memcpy(name, n, sizeof(name));
age = a;
cout