zoukankan      html  css  js  c++  java
  • Python 类变量和成员变量

    Python 类变量和成员变量

    类与对象的方法

    我们已经讨论了类与对象的功能部分,现在我们来看一下它的数据部分。事实上,它们只是与类和对象的名称空间 绑定 的普通变量,即这些名称只在这些类与对象的前提下有效。

    有两种类型的 域 ——类的变量和对象的变量,它们根据是类还是对象 拥有 这个变量而区分。

    类的变量 由一个类的所有对象(实例)共享使用。只有一个类变量的拷贝,所以当某个对象对类的变量做了改动的时候,这个改动会反映到所有其他的实例上。

    对象的变量 由类的每个对象/实例拥有。因此每个对象有自己对这个域的一份拷贝,即它们不是共享的,在同一个类的不同实例中,虽然对象的变量有相同的名称,但是是互不相关的。通过一个例子会使这个易于理解。

    #!/usr/bin/python
    # Filename: objvar.py
    
    class Person:
        '''Represents a person.'''
        population = 0
    
        def __init__(self, name):
            '''Initializes the person's data.'''
            self.name = name
            print '(Initializing %s)' % self.name
    
            # When this person is created, he/she
            # adds to the population
            Person.population += 1
    
        def __del__(self):
            '''I am dying.'''
            print '%s says bye.' % self.name
    
            Person.population -= 1
    
            if Person.population == 0:
                print 'I am the last one.'
            else:
                print 'There are still %d people left.' % Person.population
    
        def sayHi(self):
            '''Greeting by the person.
    
            Really, that's all it does.'''
            print 'Hi, my name is %s.' % self.name
    
        def howMany(self):
            '''Prints the current population.'''
            if Person.population == 1:
                print 'I am the only person here.'
            else:
                print 'We have %d persons here.' % Person.population
    
    swaroop = Person('Swaroop')
    swaroop.sayHi()
    swaroop.howMany()
    
    kalam = Person('Abdul Kalam')
    kalam.sayHi()
    kalam.howMany()
    
    swaroop.sayHi()
    swaroop.howMany()
    
    (源文件:code/objvar.py)
    
    输出
    
    $ python objvar.py
    (Initializing Swaroop)
    Hi, my name is Swaroop.
    I am the only person here.
    (Initializing Abdul Kalam)
    Hi, my name is Abdul Kalam.
    We have 2 persons here.
    Hi, my name is Swaroop.
    We have 2 persons here.
    Abdul Kalam says bye.
    There are still 1 people left.
    Swaroop says bye.
    I am the last one.
    

    类的变量 由一个类的所有对象(实例)共享使用。只有一个类变量的拷贝,所以当某个对象对类的变量做了改动的时候,这个改动会反映到所有其他的实例上。
    当实例调用完成之后或者有实例被删除时(del 实例名称)调用__del__函数

  • 相关阅读:
    分治法解决寻找数组中最大最小值的问题
    bootstrap动画进度条
    关于bootstrap中css样式与自己设置的css样式相撞问题
    css引入外部字体
    清除浮动
    四叶玫瑰数
    水仙花数
    nginx 配置文件服务器
    springboot 自定义拦截器 防止恶意请求
    springboot 自定义异常
  • 原文地址:https://www.cnblogs.com/wspblog/p/5876054.html
Copyright © 2011-2022 走看看