Python中類的繼承代碼執行個體

來源:互聯網
上載者:User
相對於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<<"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, a)
{
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, a)
{
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, 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更簡潔些。。。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.