Python设计模式 面向对象模式

Python设计模式 面向对象模式

面向对象的模式是最常用的模式。这种模式几乎在每一种编程语言中都可以找到。

如何实现面向对象的模式

现在让我们看看如何实现面向对象模式。

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

输出

上述程序产生的输出如下

Python设计模式--面向对象

解释

该代码包括类属性和实例属性,根据输出的要求进行打印。有各种特征构成了面向对象模式的一部分。这些特征将在下一章解释。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程