Python设计模式 专题
您的位置:python > Python设计模式专题 > 面向对象概念的实现
面向对象概念的实现
作者:--    发布时间:2019-11-20

在本章中,我们将重点学习使用面向对象概念的模式及其在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类变量称为robot.population,而不是self.population

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册