python类

1 . 创建类


类(Class): 用来描述具有相同的属性和方法的对象的集合。它定义了该集合中每个对象所共有的属性和方法。对象是类的实例。 使用class语句来创建一个新类,class之后为类的名称并以冒号结尾,如下实例:

  1. class ClassName:
  2. '类的帮助信息' #类文档字符串
  3. class_suite #类体

下面代码就创建了一个名为Employee的类.

  1. class Employee:
  2. # '所有员工的基类'
  3. empCount = 0
  4.  
  5. def __init__(self, name, salary):
  6. self.name = name
  7. self.salary = salary
  8. Employee.empCount += 1
  9.  
  10. def displayCount(self):
  11. print "Total Employee %d" % Employee.empCount
  12.  
  13. def displayEmployee(self):
  14. print "Name : ", self.name, ", Salary: ", self.salary

如下代码创建Employee的实例。

  1. # "创建 Employee 类的第一个对象"
  2. emp1 = Employee("Zara", 2000)
  3. # "创建 Employee 类的第二个对象"
  4. emp2 = Employee("Manni", 5000)

 

2. 访问属性


可以使用点(.)来访问对象的属性。使用如下类的名称访问类变量:

  1. # 定义类
  2. class Employee:
  3. # '所有员工的基类'
  4. empCount = 0
  5.  
  6. def __init__(self, name, salary):
  7. self.name = name
  8. self.salary = salary
  9. Employee.empCount += 1
  10.  
  11. def displayCount(self):
  12. print "Total Employee %d" % Employee.empCount
  13.  
  14. def displayEmployee(self):
  15. print "Name : ", self.name, ", Salary: ", self.salary
  16. # "创建 Employee 类的第一个对象"
  17. emp1 = Employee("Zara", 2000)
  18. # "创建 Employee 类的第二个对象"
  19. emp2 = Employee("Manni", 5000)
  20. # 访问类成员
  21. emp1.displayEmployee()
  22. emp2.displayEmployee()

我们也可以对类的属性进行修改,增加,删除。

  1. emp1.age = 7 # 添加一个 'age' 属性
  2. emp1.age = 8 # 修改 'age' 属性
  3. del emp1.age # 删除 'age' 属性

3.类的继承


面向对象的编程带来的主要好处之一是代码的重用,实现这种重用的方法之一是通过继承机制。继承完全可以理解成类之间的类型和子类型关系。

继承语法为 class 派生类名(基类名)://... 基类名写作括号里,基本类是在类定义的时候,在元组之中指明的。

派生类的声明,与他们的父类类似,继承的基类列表跟在类名之后,如下所示:

class SubClassName (ParentClass1[, ParentClass2, ...]):
'Optional class documentation string'
class_suite

 

如下继承的例子。

class Child(Parent): # 定义子类
def __init__(self):
print "调用子类构造方法"

def childMethod(self):
print '调用子类方法 child method'

c = Child() # 实例化子类
c.childMethod() # 调用子类的方法
c.parentMethod() # 调用父类方法
c.setAttr(200) # 再次调用父类的方法
c.getAttr() # 再次调用父类的方法

 

4.

方法重写


如果你的父类方法的功能不能满足你的需求,你可以在子类重写你父类的方法:

  1. class Parent: # 定义父类
  2. def myMethod(self):
  3. print '调用父类方法'
  4.  
  5. class Child(Parent): # 定义子类
  6. def myMethod(self):
  7. print '调用子类方法'
  8.  
  9. c = Child() # 子类实例
  10. c.myMethod() # 子类调用重写方法
posted @ 2015-09-05 22:49  wujinfeng  阅读(102)  评论(0)    收藏  举报