第一种:
首先定义类,然后在同一个文件中调用这个类,代码如下:
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) #无主函数,直接创建对象
emp2 = Employee("MANNY",5000)
emp1.displayEmploee()
emp2.displayEmploee()
print "Total Employee %d " % Employee.emCount
第二种:
首先定义类,然后在同一个文件中通过主函数调用这个类,代码如下:
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__': #主函数,下划线为两道
emp1 = Employee("ZARA",2000)
emp2 = Employee("MANNY",5000)
emp1.displayEmploee()
emp2.displayEmploee()
print "Total Employee %d " % Employee.emCount
第三种:
首先定义类,然后将定义部分在一个文件中
主函数调用这个类放在另一个文件中,这样的好处是,代码易读且后期更易修改维护,格式更规范,尽量使用这种方式,代码如下:
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文件为主程序,创建对象,调用函数代码如下:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
from classtest3 import Employee #这句很重要,一定要加上这句,才能访问到这个类,创建对象
if __name__ == '__main__': #主函数
emp1 = Employee("ZARA",2000)
emp2 = Employee("MANNY",5000)
emp1.displayEmploee()
emp2.displayEmploee()
print "Total Employee %d " % Employee.emCount