Python设计模式

Python面向对象的模式

Python面向对象的模式详细操作教程
面向对象的模式是最常用的模式。这种模式几乎可以在每种编程语言中找到。

如何实现面向对象的模式?

现在让我们看看如何实现面向对象的模式。
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-22
class Parrot:
   # class attribute
   species = "bird"

   # instance attribute
   def __init__(self, name, age):
      self.name = name
      self.age = age

# instantiate the Parrot class
blu = Parrot("Blu", 10)
woo = Parrot("Woo", 15)
# access the class attributes
print("Blu is a {}".format(blu.__class__.species))
print("Woo is also a {}".format(woo.__class__.species))
# access the instance attributes
print("{} is {} years old".format( blu.name, blu.age))
print("{} is {} years old".format( woo.name, woo.age))

输出

上面的程序生成以下输出
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-22
Blu is a bird
Woo is also a bird
Blu is 10 years old
Woo is 15 years old

说明

该代码包括类属性和实例属性,它们根据输出的要求进行打印。有多种功能构成面向对象模式的一部分。
下面重点介绍使用面向对象的概念及其在Python中的实现的模式。当我们围绕语句块设计程序时,这些语句块围绕函数操作数据,这称为面向过程的程序设计。在面向对象的编程中,有两个主要的实例,分别称为类和对象。

如何实现类和对象变量?

# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-22
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()

运行结果如下:

# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-22
(Initializing R2-D2)
Greetings, my masters call me R2-D2.
We have 1 robots.
(Initializing C-3PO)
Greetings, my masters call me C-3PO.
We have 2 robots.
Robots can do some work here.
Robots have finished their work. So let's destroy them.
R2-D2 is being destroyed!
There are still 1 robots working.
C-3PO is being destroyed!
C-3PO was the last one.
We have 0 robots.

说明:在这里,我们将总体类变量称为Robot.population,而不是self.population。

昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4