python继承代码_Python中类的继承代码实例

本文通过实例代码展示了Python和C++在实现继承时的语法差异,强调了Python的简洁性。Python代码更加精炼,而C++代码相对复杂。两者的运行效果相同,但Python的可读性和编写速度方面表现出优势。
摘要由CSDN通过智能技术生成

相对于C++的继承编写,Python更简洁,而且效率也是很高的,下面编写一个简单Python的继承例子。

代码如下:

#!/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, 50000)

members = [s, t]

for mem in members:

mem.tell()

运行效果:

代码如下:

[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

我们同样编写同样效果的C++例子:

代码如下:

//filename: class.cpp

#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<

}

void Member::tell()

{

cout<

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, a)

{

marks = m;

cout<

}

void Student::tell_s()

{

Member::tell();

cout<

}

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, a)

{

salary = s;

cout<

}

void Teacher::tell_t()

{

Member::tell();

cout<

}

int main(void)

{

Student s("Tom", 20, 80);

Teacher t("Mrs.Huang", 30, 50000);

s.tell_s();

t.tell_t();

return 0;

}

运行效果:

代码如下:

[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

这两者的运行效果是一样的,但是python更简洁些。。。

本条技术文章来源于互联网,如果无意侵犯您的权益请点击此处反馈版权投诉

本文系统来源:php中文网

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值