教程 > python 3 教程 > 阅读:94

python 3 面向对象——迹忆客-ag捕鱼王app官网

python从设计之初就已经是一门面向对象的语言,正因为如此,在python中创建一个类和对象是很容易的。本章节我们将详细介绍python的面向对象编程。

如果你以前没有接触过面向对象的编程语言,那你可能需要先了解一些面向对象语言的一些基本特征,在头脑里头形成一个基本的面向对象的概念,这样有助于你更容易的学习python的面向对象编程。

接下来我们先来简单的了解下面向对象的一些基本特征。


面向对象技术简介

  • 类(class): 用来描述具有相同的属性和方法的对象的集合。它定义了该集合中每个对象所共有的属性和方法。对象是类的实例。
  • 类变量:类变量在整个实例化的对象中是公用的。类变量定义在类中且在函数体之外。类变量通常不作为实例变量使用。
  • 数据成员:类变量或者实例变量, 用于处理类及其实例对象的相关的数据。
  • 方法重写:如果从父类继承的方法不能满足子类的需求,可以对其进行改写,这个过程叫方法的覆盖(override),也称为方法的重写。
  • 局部变量:定义在方法中的变量,只作用于当前实例的类。
  • 实例变量:在类的声明中,属性是用变量来表示的。这种变量就称为实例变量,是在类声明的内部但是在类的其他成员方法之外声明的。
  • 继承:即一个派生类(derived class)继承基类(base class)的字段和方法。继承也允许把一个派生类的对象作为一个基类对象对待。例如,有这样一个设计:一个dog类型的对象派生自animal类,这是模拟"是一个(is-a)"关系(例图,dog是一个animal)。
  • 实例化:创建一个类的实例,类的具体对象。
  • 方法:类中定义的函数。
  • 对象:通过类定义的数据结构实例。对象包括两个数据成员(类变量和实例变量)和方法。

创建类

使用 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
  • empcount 变量是一个类变量,它的值将在这个类的所有实例之间共享。你可以在内部类或外部类使用 employee.empcount 访问。
  • 第一种方法__init__()方法是一种特殊的方法,被称为类的构造函数或初始化方法,当创建了这个类的实例时就会调用该方法
  • self 代表类的实例,self 在定义类的方法时是必须有的,虽然在调用时不必传入相应的参数。

self代表类的实例,而非类

类的方法与普通的函数只有一个特别的区别——它们必须有一个额外的第一个参数名称, 按照惯例它的名称是 self。

class test:
    def prt(self):
        print(self)
        print(self.__class__)
 
t = test()
t.prt()

以上实例执行结果为:

<__main__.test instance at 0x10d066878>
__main__.test

从执行结果可以很明显的看出,self 代表的是类的实例,代表当前对象的地址,而 self.class 则指向类。

self 不是 python 关键字,我们把他换成 jiyik 也是可以正常执行的:

class test:
    def prt(jiyik):
        print(jiyik)
        print(jiyik.__class__)
 
t = test()
t.prt()

以上实例执行结果为:

<__main__.test instance at 0x10d066878>
__main__.test

创建实例对象

实例化类其他编程语言中一般用关键字 new,但是在 python 中并没有这个关键字,类的实例化类似函数调用方式。

以下使用类的名称 employee 来实例化,并通过 __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/python3
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  # add an 'age' attribute.
emp1.age = 8  # modify 'age' attribute.
del emp1.age  # delete 'age' attribute.

你也可以使用以下函数的方式来访问属性:

  • getattr(obj, name[, default]) : 访问对象的属性。
  • hasattr(obj,name) : 检查是否存在一个属性。
  • setattr(obj,name,value) : 设置一个属性。如果属性不存在,会创建一个新属性。
  • delattr(obj, name) : 删除属性。
hasattr(emp1, 'age')    # returns true if 'age' attribute exists
getattr(emp1, 'age')    # returns value of 'age' attribute
setattr(emp1, 'age', 8) # set attribute 'age' at 8
delattr(empl, 'age')    # delete attribute 'age'

python内置类属性

  • __dict__ : 类的属性(包含一个字典,由类的数据属性组成)
  • __doc__ :类的文档字符串
  • __name__: 类名
  • __module__: 类定义所在的模块(类的全名是'__main__.classname',如果类位于一个导入模块mymod中,那么classname.__module__ 等于 mymod)
  • __bases__ : 类的所有父类构成元素(包含了一个由所有父类组成的元组)

python内置类属性调用实例如下:

#!/usr/bin/python3
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)
emp1 = employee("zara", 2000)
emp2 = employee("manni", 5000)
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__: {
   'displaycount': , 
   '__module__': '__main__', '__doc__': 'common base class for all employees', 
   'empcount': 2, '__init__': 
   , 'displayemployee': 
   ,
   '__weakref__': 
   , '__dict__': 
   
}

python对象销毁(垃圾回收)

python 使用了引用计数这一简单技术来跟踪和回收垃圾。

在 python 内部记录着所有使用中的对象各有多少引用。 一个内部跟踪变量,称为一个引用计数器。

当对象被创建时, 就创建了一个引用计数, 当这个对象不再需要时, 也就是说, 这个对象的引用计数变为0 时, 它被垃圾回收。但是回收不是"立即"的, 由解释器在适当的时机,将垃圾对象占用的内存空间回收。

a = 40      # create object <40>
b = a       # increase ref. count  of <40> 
c = [b]     # increase ref. count  of <40> 
del a       # decrease ref. count  of <40>
b = 100     # decrease ref. count  of <40> 
c[0] = -1   # decrease ref. count  of <40> 

垃圾回收机制不仅针对引用计数为0的对象,同样也可以处理循环引用的情况。循环引用指的是,两个对象相互引用,但是没有其他变量引用他们。这种情况下,仅使用引用计数是不够的。python 的垃圾收集器实际上是一个引用计数器和一个循环垃圾收集器。作为引用计数的补充, 垃圾收集器也会留心被分配的总量很大(即未通过引用计数销毁的那些)的对象。 在这种情况下, 解释器会暂停下来, 试图清理所有未引用的循环。

示例

析构函数 __del__,__del__在对象销毁的时候被调用,当对象不再被使用时,__del__方法运行:

#!/usr/bin/python3
class point:
   def __init__( self, x=0, y=0):
      self.x = x
      self.y = y
   def __del__(self):
      class_name = self.__class__.__name__
      print (class_name, "destroyed")
pt1 = point()
pt2 = pt1
pt3 = pt1
print (id(pt1), id(pt2), id(pt3))   # prints the ids of the obejcts
del pt1
del pt2
del pt3

上述代码执行结果如下:

140338326963984 140338326963984 140338326963984
point destroyed

注意:通常你需要在单独的文件中定义一个类,然后应该使用import语句将它们导入到主程序文件中。

在上面的示例中,假设 point 类的定义包含在point.py 中,并且其中没有其他可执行代码。

#!/usr/bin/python3
import point
p1 = point.point()

类的继承

面向对象的编程带来的主要好处之一是代码的重用,实现这种重用的方法之一是通过继承机制。

通过继承创建的新类称为子类派生类,被继承的类称为基类父类超类

继承语法

class subclassname (parentclass1[, parentclass2, ...]):
   'optional class documentation string'
   class_suite

示例

#!/usr/bin/python3
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()          # instance of child
c.childmethod()      # child calls its method
c.parentmethod()     # calls parent's method
c.setattr(200)       # again call parent's method
c.getattr()          # again call parent's method

以上代码执行结果如下:

calling child constructor
calling child method
calling parent method
parent attribute : 200

类似的方式,你可以从多个父类驱动一个类,如下所示 -

class a:        # define your class a
.....
class b:         # define your class b
.....
class c(a, b):   # subclass of a and b
.....

你可以使用issubclass()或者isinstance()方法来检测。

  • issubclass() - 布尔函数判断一个类是另一个类的子类或者子孙类,语法:issubclass(sub,sup)
  • isinstance(obj, class) 布尔函数如果obj是class类的实例对象或者是一个class子类的实例对象则返回true。

方法重写

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

#!/usr/bin/python3
class parent:        # define parent class
   def mymethod(self):
      print ('calling parent method')
class child(parent): # define child class
   def mymethod(self):
      print ('calling child method')
c = child()          # instance of child
c.mymethod()         # child calls overridden method

上述代码执行结果如下:

calling child method

基础重载方法

下表列出了一些通用的功能,你可以在自己的类重写:

序号 方法 描述 & 简单的调用
1 _init_ ( self [,args...] ) 构造函数
简单的调用方法: obj = classname(args)
2 _del_( self ) 析构方法, 删除一个对象
简单的调用方法 : del obj
3 _repr_( self ) 转化为供解释器读取的形式
简单的调用方法 : repr(obj)
4 _str_( self ) 用于将值转化为适于人阅读的形式
简单的调用方法 : str(obj)
5 _cmp_ ( self, x ) 对象比较
简单的调用方法 : cmp(obj, x)

运算符重载

python同样支持运算符重载,实例如下

#!/usr/bin/python3
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)

类属性与方法

类的私有属性

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

类的方法

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

类的私有方法

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

#!/usr/bin/python3
class justcounter:
   __secretcount = 0
  
   def count(self):
      self.__secretcount  = 1
      print (self.__secretcount)
counter = justcounter()
counter.count()
counter.count()
print (counter.__secretcount)

上述代码执行结果

1
2
traceback (most recent call last):
   file "test.py", line 12, in 
      print counter.__secretcount
attributeerror: justcounter instance has no attribute '__secretcount'

python 通过在内部更改名称以包含类名来保护这些成员。您可以访问诸如object._classname__attrname 之类的属性。如果您按如下方式替换最后一行,那么它对您有用 -

.........................
print counter._justcounter__secretcount

执行上述代码时,会产生以下结果 -

1
2
2

查看笔记

扫码一下
查看教程更方便
网站地图