class Employee: //定义类 以冒号结束 '所有员工的基类' //帮助信息 empCount = 0 def __init__(self, name, salary): //调用时初始化,属性有name和salary self.name = name self.salary = salary Employee.empCount += 1 def displayCount(self): print "Total Employee %d" % Employee.empCount //%格式化打印格式 def displayEmployee(self): print "Name : ", self.name, ", Salary: ", self.salary"创建 Employee 类的第一个对象"emp1 = Employee("Zara", 2000)"创建 Employee 类的第二个对象"emp2 = Employee("Manni", 5000)emp1.displayEmployee()emp2.displayEmployee()print "Total Employee %d" % Employee.empCountemp1.age = 7 # 添加一个 'age' 属性emp1.age = 8 # 修改 'age' 属性del emp1.age # 删除 'age' 属性hasattr(emp1, 'age') # 如果存在 'age' 属性返回 True。getattr(emp1, 'age') # 返回 'age' 属性的值setattr(emp1, 'age', 8) # 添加属性 'age' 值为 8delattr(empl, 'age') # 删除属性 'age'//内置类属性#!/usr/bin/python# -*- coding: UTF-8 -*-class Employee: '所有员工的基类' empCount = 0 def __init__(self, name, salary): self.name = name self.salary = salary Employee.empCount += 1 def displayCount(self): print "Total Employee %d" % Employee.empCount def displayEmployee(self): print "Name : ", self.name, ", Salary: ", self.salaryprint "Employee.__doc__:", Employee.__doc__ //帮助文档print "Employee.__name__:", Employee.__name__ //类名print "Employee.__module__:", Employee.__module__ //模块print "Employee.__bases__:", Employee.__bases__ //类的所有父类构成元素print "Employee.__dict__:", Employee.__dict__ //类的属性//#!/usr/bin/python# -*- coding: UTF-8 -*-class Parent: # 定义父类 parentAttr = 100 def __init__(self): print "调用父类构造函数" def parentMethod(self): print '调用父类方法' def setAttr(self, attr): Parent.parentAttr = attr def getAttr(self): print "父类属性 :", Parent.parentAttrclass Child(Parent): # 定义子类 def __init__(self): print "调用子类构造方法" def childMethod(self): print '调用子类方法 child method'c = Child() # 实例化子类c.childMethod() # 调用子类的方法c.parentMethod() # 调用父类方法c.setAttr(200) # 再次调用父类的方法c.getAttr() # 再次调用父类的方法输出结果调用子类构造方法调用子类方法 child method调用父类方法父类属性 : 200//继承多个类class A: # 定义类 A.....class B: # 定义类 B.....class C(A, B): # 继承类 A 和 B.....//方法重写#!/usr/bin/pythonclass parent(): def mymethod(self): print 'this is a test' def bp(self): print 'how are you'class child(parent): def __init__(self): print 'I am bp' def mymethod(self): print 'this is not a test'c=child()c.mymethod()c.bp()输出结果I am bpthis is not a testhow are you//私有方法和属性class JustCounter: __secretCount = 0 # 私有变量 publicCount = 0 # 公开变量 def count(self): self.__secretCount += 1 self.publicCount += 1 print self.__secretCountcounter = JustCounter()counter.count()counter.count()print counter.publicCountprint counter.__secretCount # 报错,实例不能访问私有变量输出结果122Traceback (most recent call last): File "test.py", line 17, inprint counter.__secretCount # 报错,实例不能访问私有变量AttributeError: JustCounter instance has no attribute '__secretCount'