python类
1 . 创建类
类(Class): 用来描述具有相同的属性和方法的对象的集合。它定义了该集合中每个对象所共有的属性和方法。对象是类的实例。 使用class语句来创建一个新类,class之后为类的名称并以冒号结尾,如下实例:
- class ClassName:
- '类的帮助信息' #类文档字符串
- class_suite #类体
下面代码就创建了一个名为Employee的类.
- 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
如下代码创建Employee的实例。
- # "创建 Employee 类的第一个对象"
- emp1 = Employee("Zara", 2000)
- # "创建 Employee 类的第二个对象"
- emp2 = Employee("Manni", 5000)
2. 访问属性
可以使用点(.)来访问对象的属性。使用如下类的名称访问类变量:
- # 定义类
- 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
- # "创建 Employee 类的第一个对象"
- emp1 = Employee("Zara", 2000)
- # "创建 Employee 类的第二个对象"
- emp2 = Employee("Manni", 5000)
- # 访问类成员
- emp1.displayEmployee()
- emp2.displayEmployee()
我们也可以对类的属性进行修改,增加,删除。
- emp1.age = 7 # 添加一个 'age' 属性
- emp1.age = 8 # 修改 'age' 属性
- 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.
方法重写
如果你的父类方法的功能不能满足你的需求,你可以在子类重写你父类的方法:
- class Parent: # 定义父类
- def myMethod(self):
- print '调用父类方法'
- class Child(Parent): # 定义子类
- def myMethod(self):
- print '调用子类方法'
- c = Child() # 子类实例
- c.myMethod() # 子类调用重写方法

浙公网安备 33010602011771号