# -*- coding: UTF-8 -*- class Robot: population = 0 def __init__(self, name): # init function is similar to constructor in java # Added a variable name to the instance, the value is the incoming name self.name = name print "(Initializing {})".format(self.name) Robot.population += 1 # The self here is the same as the self of the __init__() function, and the name can also be obtained 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("") This constructor will call the __init__() function 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()
Recently I was reading "Concise Python Tutorial", class variables and object variables, the code in the book is shown above.
There are two types of fields: class variables and object variables, classified according to whether the class or object owns these variables.
There is a convention in python: the first parameter of the function is the instance object itself, and the name is named: self by default, which is equivalent to this in java.
The population property belongs to the Robot class and is a class variable.
The name variable belongs to an object (assigned by using self) and is therefore an object variable. Note: Object variables can only be defined in the constructor __init__().