Python 中的类(上)

xiaoxiao2021-02-27  161

原文:http://www.cnblogs.com/wilber2013/p/4677412.html

在Python中,可以通过class关键字定义自己的类,然后通过自定义的类对象类创建实例对象。

例如,下面创建了一个Student的类,并且实现了这个类的初始化函数”__init__”:

Python 1 2 3 4 5 6 7 class Student ( object ) :      count = 0      books = [ ]      def __init__ ( self , name , age ) :          self . name = name          self . age = age      pass

接下来就通过上面的Student类来看看Python中类的相关内容。

 

数据属性

在上面的Student类中,”count””books””name”和”age”都被称为类的数据属性,但是它们又分为类数据属性和实例数据属性。

类数据属性和实例数据属性

首先看一段代码,代码中分别展示了对类数据属性和实例数据属性的访问:

Python 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 Student . books . extend ( [ "python" , "javascript" ] )    print "Student book list: %s" % Student . books      # class can add class attribute after class defination Student . hobbies = [ "reading" , "jogging" , "swimming" ] print "Student hobby list: %s" % Student . hobbies     print dir ( Student )   print   wilber = Student ( "Wilber" , 28 ) print "%s is %d years old" % ( wilber . name , wilber . age )    # class instance can add new attribute # "gender" is the instance attribute only belongs to wilber wilber . gender = "male" print "%s is %s" % ( wilber . name , wilber . gender )    # class instance can access class attribute print dir ( wilber ) wilber . books . append ( "C#" ) print wilber . books   print   will = Student ( "Will" , 27 ) print "%s is %d years old" % ( will . name , will . age )    # will shares the same class attribute with wilber # will don't have the "gender" attribute that belongs to wilber print dir ( will )      print will . books

通过内建函数dir(),或者访问类的字典属性__dict__,这两种方式都可以查看类有哪些属性,代码的输出为:

对于类数据属性和实例数据属性,可以总结为:

类数据属性属于类本身,可以通过类名进行访问/修改类数据属性也可以被类的所有实例访问/修改在类定义之后,可以通过类名动态添加类数据属性,新增的类属性也被类和所有实例共有实例数据属性只能通过实例访问在实例生成后,还可以动态添加实例数据属性,但是这些实例数据属性只属于该实例

特殊的类属性

对于所有的类,都有一组特殊的属性:

类属性 含义 __name__ 类的名字(字符串) __doc__ 类的文档字符串 __bases__ 类的所有父类组成的元组 __dict__ 类的属性组成的字典 __module__ 类所属的模块 __class__ 类对象的类型

通过这些属性,可以得到 Student类的一些信息:

Python 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 class Student ( object ) :      '''     this is a Student class     '''      count = 0      books = [ ]      def __init__ ( self , name , age ) :          self . name = name          self . age = age      pass   print Student . __name__ print Student . __doc__ print Student . __bases__ print Student . __dict__ print Student . __module__ print Student . __class

代码输出为:

属性隐藏

从上面的介绍了解到,类数据属性属于类本身,被所有该类的实例共享;并且,通过实例可以去访问/修改类属性。但是,在通过实例中访问类属性的时候一定要谨慎,因为可能出现属性”隐藏”的情况。

继续使用上面的Student类,来看看属性隐藏:

Python 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 wilber = Student ( "Wilber" , 28 )   print "Student.count is wilber.count: " , Student . count is wilber . count wilber . count = 1      print "Student.count is wilber.count: " , Student . count is wilber . count print Student . __dict__ print wilber . __dict__ del wilber . count print "Student.count is wilber.count: " , Student . count is wilber . count   print   wilber . count += 3      print "Student.count is wilber.count: " , Student . count is wilber . count print Student . __dict__ print wilber . __dict__   del wilber . count print   print "Student.books is wilber.books: " , Student . books is wilber . books wilber . books = [ "C#" , "Python" ] print "Student.books is wilber.books: " , Student . books is wilber . books print Student . __dict__ print wilber . __dict__ del wilber . books print "Student.books is wilber.books: " , Student . books is wilber . books   print   wilber . books . append ( "CSS" ) print "Student.books is wilber.books: " , Student . books is wilber . books print Student . __dict__ print wilber . __dict__

代码的输出为:

分析一下上面代码的输出:

对于不可变类型的类属性Student.count,可以通过实例wilber进行访问,并且”Student.count is wilber.count”当通过实例赋值/修改count属性的时候,都将为实例wilber新建一个count实例属性,这时,”Student.count is not wilber.count”当通过”del wilber.count”语句删除实例的count属性后,再次成为”Student.count is wilber.count”同样对于可变类型的类属性Student.books,可以通过实例wilber进行访问,并且”Student. books is wilber. books”当通过实例赋值books属性的时候,都将为实例wilber新建一个books实例属性,这时,”Student. Books is not wilber. books”当通过”del wilber. books”语句删除实例的books属性后,再次成为”Student. books is wilber. books”当通过实例修改books属性的时候,将修改wilber.books指向的内存地址(即Student.books),此时,”Student. Books is wilber. books”

注意,虽然通过实例可以访问类属性,但是,不建议这么做,最好还是通过类名来访问类属性,从而避免属性隐藏带来的不必要麻烦。

 

方法

在一个类中,可能出现三种方法,实例方法、静态方法和类方法,下面来看看三种方法的不同。

实例方法

实例方法的第一个参数必须是”self”,”self”类似于C++中的”this”。

实例方法只能通过类实例进行调用,这时候”self”就代表这个类实例本身。通过”self”可以直接访问实例的属性。

Python 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 class Student ( object ) :      '''     this is a Student class     '''      count = 0      books = [ ]      def __init__ ( self , name , age ) :          self . name = name          self . age = age        def printInstanceInfo ( self ) :          print "%s is %d years old" % ( self . name , self . age )      pass   wilber = Student ( "Wilber" , 28 ) wilber . printInstanceInfo ( )

类方法

类方法以cls作为第一个参数,cls表示类本身,定义时使用@classmethod装饰器。通过cls可以访问类的相关属性。

Python 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 class Student ( object ) :      '''     this is a Student class     '''      count = 0      books = [ ]      def __init__ ( self , name , age ) :          self . name = name          self . age = age        @ classmethod      def printClassInfo ( cls ) :          print cls . __name__          print dir ( cls )      pass   Student . printClassInfo ( )      wilber = Student ( "Wilber" , 28 ) wilber . printClassInfo ( )

代码的输出为,从这段代码可以看到,类方法可以通过类名访问,也可以通过实例访问。

静态方法

与实例方法和类方法不同,静态方法没有参数限制,既不需要实例参数,也不需要类参数,定义的时候使用@staticmethod装饰器。

同类方法一样,静态法可以通过类名访问,也可以通过实例访问。

Python 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 class Student ( object ) :      '''     this is a Student class     '''      count = 0      books = [ ]      def __init__ ( self , name , age ) :          self . name = name          self . age = age        @ staticmethod      def printClassAttr ( ) :          print Student . count          print Student . books      pass   Student . printClassAttr ( )      wilber = Student ( "Wilber" , 28 ) wilber . printClassAttr ( )

这三种方法的主要区别在于参数,实例方法被绑定到一个实例,只能通过实例进行调用;但是对于静态方法和类方法,可以通过类名和实例两种方式进行调用。

 

访问控制

Python中没有访问控制的关键字,例如private、protected等等。但是,在Python编码中,有一些约定来进行访问控制。

单下划线”_”

在Python中,通过单下划线”_”来实现模块级别的私有化,一般约定以单下划线”_”开头的变量、函数为模块私有的,也就是说”from moduleName import *”将不会引入以单下划线”_”开头的变量、函数。

现在有一个模块lib.py,内容用如下,模块中一个变量名和一个函数名分别以”_”开头:

Python 1 2 3 4 5 6 7 8 9 10 numA = 10 _numA = 100   def printNum ( ) :      print "numA is:" , numA      print "_numA is:" , _numA   def _printNum ( ) :      print "numA is:" , numA print "_numA is:" , _numA

当通过下面代码引入lib.py这个模块后,所有的以”_”开头的变量和函数都没有被引入,如果访问将会抛出异常:

Python 1 2 3 4 5 6 from lib import * print numA printNum ( )   print _numA #print _printNum()

双下划线”__”

对于Python中的类属性,可以通过双下划线”__”来实现一定程度的私有化,因为双下划线开头的属性在运行时会被”混淆”(mangling)。

在Student类中,加入了一个”__address”属性:

Python 1 2 3 4 5 6 7 8 9 10 class Student ( object ) :      def __init__ ( self , name , age ) :          self . name = name          self . age = age          self . __address = "Shanghai"        pass   wilber = Student ( "Wilber" , 28 ) print wilber . __address

当通过实例wilber访问这个属性的时候,就会得到一个异常,提示属性”__address”不存在。

其实,通过内建函数dir()就可以看到其中的一些原由,”__address”属性在运行时,属性名被改为了”_Student__address”(属性名前增加了单下划线和类名)

Python 1 2 3 4 5 6 7 >>> wilber = Student ( "Wilber" , 28 ) >>> dir ( wilber ) [ '_Student__address' , '__class__' , '__delattr__' , '__dict__' , '__doc__' , '__form at__' , '__getattribute__' , '__hash__' , '__init__' , '__module__' , '__new__' , '__r educe__' , '__reduce_ex__' , '__repr__' , '__setattr__' , '__sizeof__' , '__str__' , ' __subclasshook__' , '__weakref__' , 'age' , 'name' ] >>>

所以说,即使是双下划线,也没有实现属性的私有化,因为通过下面的方式还是可以直接访问”__address”属性:

Python 1 2 3 4 >>> wilber = Student ( "Wilber" , 28 ) >>> print wilber . _Student__address Shanghai >>>

双下划线的另一个重要的目地是,避免子类对父类同名属性的冲突。

看下面一个例子:

Python 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 class A ( object ) :      def __init__ ( self ) :          self . __private ( )          self . public ( )        def __private ( self ) :          print 'A.__private()'        def public ( self ) :          print 'A.public()'   class B ( A ) :      def __private ( self ) :          print 'B.__private()'        def public ( self ) :          print 'B.public()'   b = B ( )

当实例化B的时候,由于没有定义__init__函数,将调用父类的__init__,但是由于双下划线的”混淆”效果,”self.__private()”将变成 “self._A__private()”。

看到这里,就清楚为什么会有如下输出了:

“_”和” __”的使用 更多的是一种规范/约定,不没有真正达到限制的目的:

“_”:以单下划线开头的表示的是protected类型的变量,即只能允许其本身与子类进行访问;同时表示弱内部变量标示,如,当使用”from moduleNmae import *”时,不会将以一个下划线开头的对象引入。 “__”:双下划线的表示的是私有类型的变量。只能是允许这个类本身进行访问了,连子类也不可以,这类属性在运行时属性名会加上单下划线和类名。

 

总结

本文介绍了Python中class的一些基本点:

实例数据属性和类数据属性的区别,以及属性隐藏实例方法,类方法和静态方法直接的区别Python中通过”_”和”__”实现的访问控制
转载请注明原文地址: https://www.6miu.com/read-12567.html

最新回复(0)