• Python学习总结19:类(一)


        在Python中,可以通过class关键字定义自己的类,通过类私有方法“__init__”进行初始化。可以通过自定义的类对象类创建实例对象

    class Student(object):
        count = 0
        books = []
        def __init__(self, name, age):
            self.name = name
            self.age = age
        pass

    1. 数据属性

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

    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)
     
     
    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
    
    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__,这两种方式都可以查看类有哪些属性。

    >>> print dir(Student)
    ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'books', 'count', 'hobbies']

        1)特殊的类属性

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

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

         2)属性隐藏

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

    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__

    2. 方法

        在一个类中,可能出现三种方法,实例方法、静态方法和类方法。

        1)实例方法

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

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

    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()

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

    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()

         3)静态方法

     与实例方法和类方法不同,静态方法没有参数限制,既不需要实例参数,也不需要类参数,定义的时候使用@staticmethod装饰器。
    同类方法一样,静态法可以通过类名访问,也可以通过实例访问。
    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()

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

    3. 访问控制

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

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

    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这个模块后,所有的以”_”开头的变量和函数都没有被引入,如果访问将会抛出异常:

    from lib import *
    print numA
    printNum()
     
    print _numA
    #print _printNum()

         双下划线”__”

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

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

    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”(属性名前增加了单下划线和类名)

    >>> 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”属性: 

    >>> wilber = Student("Wilber", 28)
    >>> print wilber._Student__address
    Shanghai

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

    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中通过”_”和”__”实现的访问控制
  • 相关阅读:
    [Windows Server 2012] SQL Server 备份和还原方法
    [Windows Server 2012] 更改服务器密码
    [Windows Server 2012] 初识Windows Server 2012
    [Windows Server 2012] 更换PHP版本方法
    [Windows Server 2008] IP安全策略限制端口方法
    [Windows Server 2008] Windows防火墙设置
    [Windows Server 2003] 初识Windows Server 2003
    [Windows Server 2003] 手工创建安全网站
    Codeforces Round #324 (Div. 2) Dima and Lisa 哥德巴赫猜想
    Codeforces Round #324 (Div. 2) Marina and Vasya 乱搞推理
  • 原文地址:https://www.cnblogs.com/zhuxiaohou110908/p/5778290.html
Copyright © 2020-2023  润新知