开发手册 欢迎您!
软件开发者资料库

Python设计模式 - 面向对象的概念实现

Python设计模式面向对象的概念实现 - 从简单和简单的步骤学习Python设计模式从基本到高级概念,包括简介,Python的Gist,模型视图控制器,单例,工厂,构建器,原型,外观,命令,适配器,装饰,代理,责任链,观察员,状态,战略,模板,飞重,抽象工厂,面向对象的模式,面向对象的概念实施,迭代器模式,词典,列表数据结构,集,队列,字符串和序列化,Python中的并发,反模式,异常处理。

在本章中,我们将重点介绍使用面向对象概念的模式及其在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.