在本章中,我们将重点学习使用面向对象概念的模式及其在python中的实现。 当我们围绕函数设计围绕语句块的程序时,它被称为面向过程的编程。 在面向对象编程中,有两个主要的实例叫做类和对象。
类和对象变量的实现如下 -
class robot:
population = 0
def __init__(self, name):
self.name = name
print("(initializing {})".format(self.name))
robot.population += 1
def die(self):
print("{} is being destroyed!".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 masters call me {}.".format(self.name))
@classmethod
def how_many(cls):
print("we have {:d} robots.".format(cls.population))
droid1 = robot("r2-d2")
droid1.say_hi()
robot.how_many()
droid2 = robot("c-3po")
droid2.say_hi()
robot.how_many()
print("\nrobots can do some work here.\n")
print("robots have finished their work. so let's destroy them.")
droid1.die()
droid2.die()
robot.how_many()
执行上述程序生成以下输出 -
说明
此图有助于展示类和对象变量的性质。
population
类变量称为robot.population
,而不是self.population
。