python高级教程-面向对象

创建类:

class  类名:

    类体(由类成员,方法,数据属性组成)

例如:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
class Employee:
   '所有员工的基类'                                                                                                                                                                 类名.类变量
   empCount = 0                               #类变量  ,它的值将在这个类的所有实例之间共享,可以在内部类或外部类使用Employee.empCount 访问
 
   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__()方法是一种特殊的方法,被称为类的构造函数或初始化方法,当创建了这个类的实例时就会调用该方法

self 代表类的实例,self 在定义类的方法时是必须有的,虽然在调用时不必传入相应的参数。

 

创建实例对象:类的实例化类似函数的调用方式。

                         以下使用类的名称 Employee 来实例化,并通过 __init__ 方法接受参数。

                      

                        "创建 Employee 类的第一个对象"
                         emp1 = Employee("Zara", 2000)
                       "创建 Employee 类的第二个对象"
                         emp2 = Employee("Manni", 5000)

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

                   emp1.displayEmployee()
                   emp2.displayEmployee()
                   print "Total Employee %d" % Employee.empCount

例如:

#!/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.salary
 
"创建 Employee 类的第一个对象"
emp1 = Employee("Zara", 2000)
"创建 Employee 类的第二个对象"
emp2 = Employee("Manni", 5000)
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount

 

添加,修改,删除类属性:

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

 

 getattr(obj, name[, default]) : 访问对象的属性。
  hasattr(obj,name) : 检查是否存在一个属性。
  setattr(obj,name,value) : 设置一个属性。如果属性不存在,会创建一个新属性。
  delattr(obj, name) : 删除属性。
例如:
hasattr(emp1, 'age')    # 如果存在 'age' 属性返回 True。
getattr(emp1, 'age')    # 返回 'age' 属性的值
setattr(emp1, 'age', 8) # 添加属性 'age' 值为 8
delattr(empl, 'age')    # 删除属性 'age'

 

类的继承:实现代码的重用

继承中的特点:

1.基类的构造函数(__init()__方法)不会被调用,需要在派生类的构造中亲自专门调用。

2.在调用基类方法时,需要加上基类的类名前缀,且需要带上self参数变量。区别在于调用普通函数时不需要带上self参数。

3.先在本类中查找调用的方法,找不到才去基类中找。

 

派生类的声明:

class  派生类名(基类名1,基类名2,基类名3.........):

 

例如:

#!/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.parentAttr
 
class Child(Parent): # 定义子类
   def __init__(self):
      print "调用子类构造方法"
 
   def childMethod(self):
      print '调用子类方法'
 
c = Child()          # 实例化子类
c.childMethod()      # 调用子类的方法
c.parentMethod()     # 调用父类方法
c.setAttr(200)       # 再次调用父类的方法 - 设置属性值
c.getAttr()          # 再次调用父类的方法 - 获取属性值

 

也可以继承多个类,即多继承

class A:        # 定义类 A
.....

class B:         # 定义类 B
.....

class C(A, B):   # 继承类 A 和 B    只要用逗号隔开

 

方法重写:父类的方法不能满足子类的需求。

例如:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
class Parent:        # 定义父类
   def myMethod(self):
      print '调用父类方法'
 
class Child(Parent): # 定义子类
   def myMethod(self):
      print '调用子类方法'
 
c = Child()          # 子类实例
c.myMethod()         # 子类调用重写方法

 

重载方法:__str__(self)    简单的调用方法  str(obj)

 

 

类的属性和方法:

类的私有属性:两个下划线开头,声明该属性为私有,不能在类的外部使用或直接访问,在类内部的方法中使用时 self.__private_attrs。

类的私有方法:两个下划线开头,声明该方法为私有方法,不能在类的外部调用,在类的内部调用 self.__private_methods

类方法:在类的内部,使用def可以为类定义一个方法,与一般函数的定义不同,类方法必须包含参数self,且为第一个参数。

 

例如:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
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  # 报错,实例不能访问私有变量

Python不允许实例化的类访问私有数据,但你可以使用 object._className__attrName 访问属性,将如下代码替换以上代码的最后一行代码:

print counter._JustCounter__secretCount

 

单下划线、双下划线、头尾双下划线说明:

__foo__: 定义的是特列方法,类似 __init__() 之类的。

_foo: 以单下划线开头的表示的是 protected 类型的变量,即保护类型只能允许其本身与子类进行访问,不能用于 from module import *

__foo: 双下划线的表示的是私有类型(private)的变量, 只能是允许这个类本身进行访问了。

 

posted on 2017-10-23 14:06  步行者811  阅读(945)  评论(0编辑  收藏  举报

导航