相对于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 <string.h>
#include <iostream>
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<<"Member init:"<<name<<endl;
}
void Member::tell()
{
cout<<"Name:"<<name<<","<<"Age:"<<age<<",";
}
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<<"Student init:"<<n<<endl;
}
void Student::tell_s()
{
Member::tell();
cout<<"Marks:"<<marks<<endl;
}
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<<"Teacher init:"<<n<<endl;
}
void Teacher::tell_t()
{
Member::tell();
cout<<"Salary:"<<salary<<endl;
}
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更简洁些。。。
Python,类,继承
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
更新日志
- 雨林唱片《赏》新曲+精选集SACD版[ISO][2.3G]
- 罗大佑与OK男女合唱团.1995-再会吧!素兰【音乐工厂】【WAV+CUE】
- 草蜢.1993-宝贝对不起(国)【宝丽金】【WAV+CUE】
- 杨培安.2009-抒·情(EP)【擎天娱乐】【WAV+CUE】
- 周慧敏《EndlessDream》[WAV+CUE]
- 彭芳《纯色角3》2007[WAV+CUE]
- 江志丰2008-今生为你[豪记][WAV+CUE]
- 罗大佑1994《恋曲2000》音乐工厂[WAV+CUE][1G]
- 群星《一首歌一个故事》赵英俊某些作品重唱企划[FLAC分轨][1G]
- 群星《网易云英文歌曲播放量TOP100》[MP3][1G]
- 方大同.2024-梦想家TheDreamer【赋音乐】【FLAC分轨】
- 李慧珍.2007-爱死了【华谊兄弟】【WAV+CUE】
- 王大文.2019-国际太空站【环球】【FLAC分轨】
- 群星《2022超好听的十倍音质网络歌曲(163)》U盘音乐[WAV分轨][1.1G]
- 童丽《啼笑姻缘》头版限量编号24K金碟[低速原抓WAV+CUE][1.1G]