python的物件導向基礎

來源:互聯網
上載者:User

標籤:utf-8   __init__   src   技術分享   pre   idt   內部類   count   員工   

1.類

  描述具有相同屬性與方法的對象的集合。

 

2.建立類

  使用class來建立一個新類,class之後為類的名稱並以冒號結尾

 

3.程式

 1 #!/usr/bin/python 2 # -*- coding: UTF-8 -*- 3  4 class Employee: 5     ‘所有員工的基類‘ 6     empCount = 0 7  8     def __init__(self, name, salary): 9         self.name = name10         self.salary = salary11         Employee.empCount += 112 13     def displayCount(self):14         print "Total Employee %d" % Employee.empCount15 16     def displayEmployee(self):17         print "Name : ", self.name, ", Salary: ", self.salary

 

4.執行個體化

  不需要new、

 

5.程式

 1 # -*- coding: utf-8 -*- 2 from ClassTest1 import Employee 3 "建立 Employee 類的第一個對象" 4 emp1 = Employee("Zara", 2000) 5 emp1.displayCount() 6 emp1.displayEmployee() 7 "建立 Employee 類的第二個對象" 8 emp2 = Employee("Manni", 5000) 9 emp2.displayCount()10 emp2.displayEmployee()11 12 print Employee.empCount

 

6.運行結果

  注意點:empCount變數是一個類變數,它的值可以在類的所有執行個體之間共用,可以在內部類或者外部類使用Employee.empCount訪問。

  

 

7.

 

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.