Python中类的继承代码实例
相对于C++的继承编写,Python更简洁,而且效率也是很高的,下面编写一个简单Python的继承例子。
#!/usr/bin/python #filename:pyclass.py classMember: def__init__(self,name,age): self.name=name self.age=age print'Memberinit:%s'%self.name deftell(self): print'Name:%s,Age:%d'%(self.name,self.age), classStudent(Member): def__init__(self,name,age,marks): Member.__init__(self,name,age) self.marks=marks print'Studentinit:%s'%self.name deftell(self): Member.tell(self) print'Marks:%d'%self.marks classTeacher(Member): def__init__(self,name,age,salary): Member.__init__(self,name,age) self.salary=salary print'Teacherinit:%s'%self.name deftell(self): Member.tell(self) print'Salary:%d'%self.salary s=Student('Tom',20,80) t=Teacher('Mrs.Huang',30,50000) members=[s,t] formeminmembers: mem.tell()
运行效果:
[root@localhosthhl]#pythonpyclass.py Memberinit:Tom Studentinit:Tom Memberinit:Mrs.Huang Teacherinit:Mrs.Huang Name:Tom,Age:20Marks:80 Name:Mrs.Huang,Age:30Salary:50000
我们同样编写同样效果的C++例子:
//filename:class.cpp #include<string.h> #include<iostream> usingnamespacestd; classMember { public: Member(char*n,inta); voidtell(); private: charname[10]; intage; }; Member::Member(char*n,inta) { memcpy(name,n,sizeof(name)); age=a; cout<<"Memberinit:"<<name<<endl; } voidMember::tell() { cout<<"Name:"<<name<<","<<"Age:"<<age<<","; } classStudent:publicMember { public: Student(char*n,inta,intm); voidtell_s(); private: intmarks; }; Student::Student(char*n,inta,intm):Member(n,a) { marks=m; cout<<"Studentinit:"<<n<<endl; } voidStudent::tell_s() { Member::tell(); cout<<"Marks:"<<marks<<endl; } classTeacher:publicMember { public: Teacher(char*n,inta,ints); voidtell_t(); private: intsalary; }; Teacher::Teacher(char*n,inta,ints):Member(n,a) { salary=s; cout<<"Teacherinit:"<<n<<endl; } voidTeacher::tell_t() { Member::tell(); cout<<"Salary:"<<salary<<endl; } intmain(void) { Students("Tom",20,80); Teachert("Mrs.Huang",30,50000); s.tell_s(); t.tell_t(); return0; }
运行效果:
[root@localhosthhl]#./class Memberinit:Tom Studentinit:Tom Memberinit:Mrs.Huang Teacherinit:Mrs.Huang Name:Tom,Age:20,Marks:80 Name:Mrs.Huang,Age:30,Salary:50000
这两者的运行效果是一样的,但是python更简洁些。。。