Python的类变量和实例变量

作者: 码农小杨 | 来源:发表于2018-01-06 22:19 被阅读14次

    首先我们看一段代码以及输出:

    In [2]: class Student():
       ...:     name = "张三"
       ...:     age = 0
       ...:     def __init__(self, name, age):
       ...:         name = name 
       ...:         age = age
       ...:         
    
    In [3]: student = Student("李四", 19)
    
    In [4]: student.name
    Out[4]: '张三'
    
    In [5]: Student.name
    Out[5]: '张三'
    

    看到这里可能有的同学会说是变量的作用域问题,事实上是实例变量和类变量的区别问题。

    我们接着看看对象student的变量有哪些:

    In [6]: student.__dict__
    Out[6]: {}
    

    为空!

    为什么为空呢?(暂时思考下)
    我们再看看类Student的变量:

    In [7]: Student.__dict__
    Out[7]: 
    mappingproxy({'__dict__': <attribute '__dict__' of 'Student' objects>,
                  '__doc__': None,
                  '__init__': <function __main__.Student.__init__>,
                  '__module__': '__main__',
                  '__weakref__': <attribute '__weakref__' of 'Student' objects>,
                  'age': 0,
                  'name': '张三'})
    

    这里我们要说一下实例变量的查找机制:
    当在实例变量中查找不到某一变量时候,就会去类变量里查找,当再查找不到的时候就会在父类中查找,因此输出的name为张三。

    之所以为空,是因为我们实例化对象的时候为指明实例变量的保存。现在修改一下实例化函数。

    In [10]: class Student():
        ...:     name = "张三"
        ...:     age = 0
        ...:     def __init__(self, name, age):
        ...:         self.name = name 
        ...:         self.age = age
        ...:         
        ...:         
        ...:         
    
    In [11]: student = Student("李四", 19)
    
    In [12]: student.name
    Out[12]: '李四'
    
    In [13]: Student.name
    Out[13]: '张三'
    

    我们传入的self只和实例化的对象有关和类无关,代表实例。

    如何在实例方法中调用类变量呢?

    In [14]: class Student():
        ...:     name = "张三"
        ...:     age = 0
        ...:     sums = 123
        ...:     def __init__(self, name, age):
        ...:         self.name = name 
        ...:         self.age = age
        ...:         print(Student.sums)
        ...:         print(self.__class__.sums)
        ...:         
        ...:         
        ...:         
        ...:         
    
    In [15]: student = Student('李四', 19)
    123
    123
    

    相关文章

      网友评论

        本文标题:Python的类变量和实例变量

        本文链接:https://www.haomeiwen.com/subject/uljunxtx.html