第一種:
首先定義類,然后在同一個文件中調(diào)用這個類辨萍,代碼如下:
classtest.py文件中代碼如下:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
class Employee: ? ?#定義類
emCount = 0
def __init__(self,name,salary):
self.name = name
self.salary = salary
Employee.emCount +=1
def displayCount(self):
print "Total Employee %d" % Emplpoyee.emCount
def displayEmploee(self):
print "Name : ",self.name,",salary : ",self.salary
emp1 = Employee("ZARA",2000) ? ? #無主函數(shù)娄猫,直接創(chuàng)建對象
emp2 = Employee("MANNY",5000)
emp1.displayEmploee()
emp2.displayEmploee()
print "Total Employee %d " % Employee.emCount
第二種:
首先定義類卓起,然后在同一個文件中通過主函數(shù)調(diào)用這個類兴蒸,代碼如下:
classtest2.py文件中代碼如下:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
class Employee:
emCount = 0
def __init__(self,name,salary):
self.name = name
self.salary = salary
Employee.emCount +=1
def displayCount(self):
print "Total Employee %d" % Emplpoyee.emCount
def displayEmploee(self):
print "Name : ",self.name,",salary : ",self.salary
if __name__ == '__main__':? ? #主函數(shù),下劃線為兩道
emp1 = Employee("ZARA",2000)
emp2 = Employee("MANNY",5000)
emp1.displayEmploee()
emp2.displayEmploee()
print "Total Employee %d " % Employee.emCount
第三種:
首先定義類裳瘪,然后將定義部分在一個文件中
主函數(shù)調(diào)用這個類放在另一個文件中履因,這樣的好處是,代碼易讀且后期更易修改維護盹愚,格式更規(guī)范,盡量使用這種方式站故,代碼如下:
classtest3.py文件定義類中代碼如下:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
class Employee:
emCount = 0
def __init__(self,name,salary):
self.name = name
self.salary = salary
Employee.emCount +=1
def displayCount(self):
print "Total Employee %d" % Emplpoyee.emCount
def displayEmploee(self):
print "Name : ",self.name,",salary : ",self.salary
main.py文件為主程序皆怕,創(chuàng)建對象毅舆,調(diào)用函數(shù)代碼如下:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
from classtest3 import Employee #這句很重要,一定要加上這句愈腾,才能訪問到這個類憋活,創(chuàng)建對象?
if __name__ == '__main__': ? ? #主函數(shù)
emp1 = Employee("ZARA",2000)
emp2 = Employee("MANNY",5000)
emp1.displayEmploee()
emp2.displayEmploee()
print "Total Employee %d " % Employee.emCount