使用class语句来创建一个新类,class之后为类的名称并以冒号结尾,如下实例:
class ClassName: 'Optional class documentation string'#类文档字符串 class_suite #类体
类的帮助信息可以通过ClassName.__doc__查看。
class_suite 由类成员,方法,数据属性组成。
以下是一个简单的Python类实例:
class Employee:
'Common base class for all employees'
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
要创建一个类的实例,你可以使用类的名称,并通过__init__方法接受参数。
"This would create first object of Employee class"
emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)
您可以使用点(.)来访问对象的属性。使用如下类的名称访问类变量:
emp1.displayEmployee() emp2.displayEmployee() print "Total Employee %d" % Employee.empCount
完整实例:
#!/usr/bin/python
class Employee:
'Common base class for all employees'
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
"This would create first object of Employee class"
emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount
执行以上代码输出结果如下:
Name : Zara ,Salary: 2000 Name : Manni ,Salary: 5000 Total Employee 2
你可以添加,删除,修改类的属性,如下所示:
emp1.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' 值为 8 delattr(empl, 'age') # 删除属性 'age'
Python内置类属性调用实例如下:
#!/usr/bin/python
class Employee:
'Common base class for all employees'
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__
执行以上代码输出结果如下:
Employee.__doc__: Common base class for all employees
Employee.__name__: Employee
Employee.__module__: __main__
Employee.__bases__: ()
Employee.__dict__: {'__module__': '__main__', 'displayCount':
<function displayCount at 0xb7c84994>, 'empCount': 2,
'displayEmployee': <function displayEmployee at 0xb7c8441c>,
'__doc__': 'Common base class for all employees',
'__init__': <function __init__ at 0xb7c846bc>}
同Java语言一样,Python使用了引用计数这一简单技术来追踪内存中的对象。
一个内部跟踪变量,称为一个引用计数器。
面向对象的编程带来的主要好处之一是代码的重用,实现这种重用的方法之一是通过继承机制。继承完全可以理解成类之间的类型和子类型关系。
需要注意的地方:继承语法 class 派生类名(基类名)://... 基类名写作括号里,基本类是在类定义的时候,在元组之中指明的。
在python中继承中的一些特点:
如果在继承元组中列了一个以上的类,那么它就被称作"多重继承" 。
语法:
派生类的声明,与他们的父类类似,继承的基类列表跟在类名之后,如下所示:
class SubClassName (ParentClass1[, ParentClass2, ...]): 'Optional class documentation string' class_suite
实例:
#!/usr/bin/python
class Parent: # define parent class
parentAttr = 100
def __init__(self):
print "Calling parent constructor"
def parentMethod(self):
print 'Calling parent method'
def setAttr(self, attr):
Parent.parentAttr = attr
def getAttr(self):
print "Parent attribute :", Parent.parentAttr
class Child(Parent): # define child class
def __init__(self):
print "Calling child constructor"
def childMethod(self):
print 'Calling child method'
c = Child() # 实例化子类
c.childMethod() # 调用子类的方法
c.parentMethod() # 调用父类方法
c.setAttr(200) # 再次调用父类的方法
c.getAttr() # 再次调用父类的方法
以上代码执行结果如下:
Calling child constructor Calling child method Calling parent method Parent attribute : 200
你可以继承多个类
class A: # define your class A ..... class B: # define your calss B ..... class C(A, B): # subclass of A and B .....
你可以使用issubclass()或者isinstance()方法来检测。
如果你的父类方法的功能不能满足你的需求,你可以在子类重载你父类的方法:
实例:
#!/usr/bin/python
class Parent: # 定义父类
def myMethod(self):
print 'Calling parent method'
class Child(Parent): # 定义子类
def myMethod(self):
print 'Calling child method'
c = Child() # 子类实例
c.myMethod() # 子类调用重载方法
执行以上代码输出结果如下:
Calling child method
下表列出了一些通用的功能,你可以在自己的类重写:
| 序号 | 方法, 描述 & 简单的调用 |
|---|---|
| 1 | __init__ ( self [,args...] ) 构造函数 简单的调用方法: obj = className(args) |
| 2 | __del__( self ) 析构方法, 删除一个对象 简单的调用方法 : dell obj |
| 3 | __repr__( self ) 转化为供解释器读取的形式 简单的调用方法 : repr(obj) |
| 4 | __str__( self ) 用于将值转化为适于人阅读的形式 简单的调用方法 : str(obj) |
| 5 | __cmp__ ( self, x ) 对象比较 简单的调用方法 : cmp(obj, x) |
Python同样支持运算符重载,实例如下:
#!/usr/bin/python
class Vector:
def __init__(self, a, b):
self.a = a
self.b = b
def __str__(self):
return 'Vector (%d, %d)' % (self.a, self.b)
def __add__(self,other):
return Vector(self.a + other.a, self.b + other.b)
v1 = Vector(2,10)
v2 = Vector(5,-2)
print v1 + v2
以上代码执行结果如下所示:
Vector(7,8)
在python中实现数据隐藏很简单,不需要在前面加什么关键字,只要把类变量名或成员函数前面加两个下划线即可实现数据隐藏的功能,这样,对于类的实例来说,其变量名和成员函数是不能使用的,对于其类的继承类来说,也是隐藏的,这样,其继承类可以定义其一模一样的变量名或成员函数名,而不会引起命名冲突。 实例:
#!/usr/bin/python
class JustCounter:
__secretCount = 0
def count(self):
self.__secretCount += 1
print self.__secretCount
counter = JustCounter()
counter.count()
counter.count()
print counter.__secretCount
Python 通过改变名称来包含类名:
1
2
Traceback (most recent call last):
File "test.py", line 12, in <module>
print counter.__secretCount
AttributeError: JustCounter instance has no attribute '__secretCount'
Python不允许实例化的类访问隐藏数据,但你可以使用object._className__attrName访问属性,将如下代码替换以上代码的最后一行代码:
......................... print counter._JustCounter__secretCount
执行以上代码,执行结果如下:
1 2 2