python裡面建立類建立對象繼承類

來源:互聯網
上載者:User

首先定義一個類:

每個類下面定義方法,

每個類下面首先定義一個構造方法,再定義其他的方法一般有set方法和get方法。

Set方法用於重新設定變數的值,尤其當一個變數定義成私人變數的時候只能通過set方法來改變值

Get方法用於輸出結果


 

# coding:utf8'''2.編寫一個程式,用於建立一個名為Employee的父類和兩個名為Manager和Director的子類。Employee類包含3個屬性和一個方法,屬性為name、basic(基本工資)和address,方法名為show(),用於顯示這些屬性的值。Manager類有一個稱為department(部門)的附加屬性。Director類有一個稱為transportAllowance(交通津貼)的附加屬性。建立Manager和Director類的對象,並顯示其詳細資料。定義一個父類下面定義一些方法'''class Employee():    def __init__(self,name,basic,address):        self.name=name        self.basic=basic        self.address=address    def show(self,name,basic,address):        print(self.name)        print(self.basic)        print(self.address)class Manager(Employee):    def __init__(self,name,basic,address,department):        Employee.__init__(self,name,basic,address)        self.department=department    def show2(self,name,basic,address,department):        self.show('cs',1000,'beijing')#繼承父類的show方法        print self.departmentclass Director(Employee):    def __init__(self,name,basic,address,transportAllowance):       Employee.__init__(self,name,basic,address)       self.transportAllowance=transportAllowance    def show3(self,name,basic,address,transportAllowance):        self.show('cs',1000,'beijing')        print(self.transportAllowance)base=Employee('cs',1000,'beijing')base.show('cs',1000,'beijing')m=Manager('cs',1000,'beijing','c1')m.show2('cs',1000,'beijing','c1')d=Director('cs',1000,'beijing','c2')d.show3('cs',1000,'beijing','c2')

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.