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.empCount
emp1.age = 7
emp1.age = 8
del emp1.age
hasattr(emp1, 'age')
getattr(emp1, 'age')
setattr(emp1, 'age', 8)
delattr(empl, 'age')
//内置类属性
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.salary
print "Employee.__doc__:", Employee.__doc__ //帮助文档
print "Employee.__name__:", Employee.__name__ //类名
print "Employee.__module__:", Employee.__module__ //模块
print "Employee.__bases__:", Employee.__bases__ //类的所有父类构成元素
print "Employee.__dict__:", Employee.__dict__ //类的属性
//
class Parent:
parentAttr = 100
def __init__(self):
print "调用父类构造函数"
def parentMethod(self):
print '调用父类方法'
def setAttr(self, attr):
Parent.parentAttr = attr
def getAttr(self):
print "父类属性 :", Parent.parentAttr
class 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:
.....
class B:
.....
class C(A, B):
.....
//方法重写
class 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 bp
this is not a test
how are you
//私有方法和属性
class JustCounter:
__secretCount = 0
publicCount = 0
def count(self):
self.__secretCount += 1
self.publicCount += 1
print self.__secretCount
counter = JustCounter()
counter.count()
counter.count()
print counter.publicCount
print counter.__secretCount
输出结果
1
2
2
Traceback (most recent call last):
File "test.py", line 17, in <module>
print counter.__secretCount
AttributeError: JustCounter instance has no attribute '__secretCount'