zoukankan      html  css  js  c++  java
  • 类与对象的变量

    #!/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()

    给C++/Java/C#程序员的注释
    Python中所有的类成员(包括数据成员)都是 公共的 ,所有的方法都是 有效的 。
    只有一个例外:如果你使用的数据成员名称以 双下划线前缀 比如__privatevar,Python的名称管理体系会有效地把它作为私有变量。
    这样就有一个惯例,如果某个变量只想在类或对象中使用,就应该以单下划线前缀。而其他的名称都将作为公共的,可以被其他类/对象使用。记住这只是一个惯例,并不是Python所要求的(与双下划线前缀不同)。
    同样,注意__del__方法与 destructor 的概念类似。

  • 相关阅读:
    &【12】Python 函数
    &【11】Python 流程控制
    &【09】Python 数据类型之dictionary
    &【07】Python 数据类型之元组
    &【08】Python 数据类型之set
    &【06】Python 数据类型之list
    &【05】Python 彻底搞懂分片操作
    &【04】Python 数据结构之序列
    SpringBoot-HelloWorld(三)
    SpringBoot-了解微服务(二)
  • 原文地址:https://www.cnblogs.com/nku-wangfeng/p/7689990.html
Copyright © 2011-2022 走看看