您的位置:首页 > 编程语言 > Python开发

简明的Python教程当中的几个疑惑点分析#1

2017-01-10 17:53 441 查看

#1简明的Python教程中的第11章面向对象编程学习中的类与对象的方法里面

有这么一个案例:使用类与对象的变量

#coding:utf-8
#类与对象的变量学习
class Person:
population=0 #定义初始值,population=0

def __init__(self,name):
self.name=name
print 'My name is %s'%self.name #会被调用
Person.population+=1#Person.population=0+1=1
#1Person.population+=1相当于Person中的population=population+1,population初始值是0,0+1=1变成了1

def __del__(self):
print 'hello world %s'%self.name

Person.population-=1#1-1=0  #现在的1变成了0原理等同于上面的#1
#虽然population=1变成了population=0但是,大家发现没?他在__del__方法里面,没啥用啊,一旦我创建实例即对象的时候,1还是1,不会变成0

if Person.population==0:
print 'I am the last one'
else:
print 'There are still %d people left'%Person.population
#使用特殊的方法名__del__,顾名思义,del就是删除的意思,当我们创建实例即对象时自动调用
def sayHi(self):
print 'Hi,my name is %s'%self.name #会被调用

def howMany(self):
if Person.population==1:
#所以population=1还是等于1
print 'I am the only person here' #将会被调用
else:
print 'We have %d persons here'%Person.population

redchen=Person('redchen')
redchen.sayHi()
redchen.howMany()
maniacs=Person('Maniacs')

 

让我们看看输出部分:

======= RESTART: C:\Users\Administrator\Desktop\使用类与对象的变量.py =======
My name is redchen
Hi,my name is redchen
I am the only person here
My name is Maniacs
>>>

 

仔细看代码上面的注释部分。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: