Python Design Patterns 简明教程

Object Oriented Concepts Implementation

在本章中,我们将重点关注使用面向对象概念的模式及其在 Python 中的实现。当我们围绕语句块设计我们的程序时,这些语句块围绕函数处理数据,这称为过程化编程。在面向对象编程中,有两个称为类和对象的主实例。

In this chapter, we will focus on patterns using object oriented concepts and its implementation in Python. When we design our programs around blocks of statements, which manipulate the data around functions, it is called procedure-oriented programming. In object-oriented programming, there are two main instances called classes and objects.

How to implement classes and object variables?

类和对象变量的实现如下 −

The implementation of classes and object variables are as follows −

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()

Output

上述程序生成以下输出 −

The above program generates the following output −

object oriented concepts implementation

Explanation

此说明有助于演示类和对象变量的性质。

This illustration helps to demonstrate the nature of class and object variables.

  1. “population” belongs to the “Robot” class. Hence, it is referred to as a class variable or object.

  2. Here, we refer to the population class variable as Robot.population and not as self.population.