# -*- coding: UTF-8 -*- class Robot: population = 0 def __init__(self, name): # init函数类似于java中的构造函数 # 给实例中新增了变量name,值是传入的name self.name = name print "(Initializing {})".format(self.name) Robot.population += 1 # 这里的self,与__init__()函数的self是同一个,也能获取到name def die(self): print "{} is being destoryed!".format(self.name) Robot.population -= 1 if Robot.population == 0: print "{} was the last one.".format(self.name) else: print "There are still {:d} robots working.".format(Robot.population) def say_hi(self): print "Greetings, my master call me {}.".format(self.name) @classmethod def how_many(cls): print 'We have {:d} robots.'.format(cls.population) droid1 = Robot("R2-D2") #Robot("")这个构造函数,就会调用__init__()函数 droid1.say_hi() Robot.how_many() droid2 = Robot("C-3PO") droid2.say_hi() Robot.how_many() print 'Robots can do some work here.' print "Robots have finished their work.So let's destroy them." droid1.die() droid2.die() Robot.how_many()
最近在看《简明Python教程》,类变量与对象变量,书中的代码如上所示。
字段有两种类型:类变量与对象变量,分类的依据是根据类还是对象拥有这些变量。
python中有一个约定俗成的规定:函数的第一个参数就是实例对象本身,默认的把这个名字命名为:self,相当于java中的this。
population属性属于Robot类,是类变量。
name变量属于一个对象(通过使用self分配),因此是一个对象变量。注意:只能在构造方法__init__()中,给对象变量定义。