Python Design Patterns 简明教程
Python Design Patterns - Object Oriented
面向对象模式是最常用的模式。几乎每个编程语言中都可以找到这个模式。
The object oriented pattern is the most commonly used pattern. This pattern can be found in almost every programming language.
How to implement the object oriented pattern?
现在让我们来看看如何实施面向对象模式。
Let us now see how to implement the object oriented pattern.
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))
Explanation
该代码包含类属性和实例属性,它们根据输出要求进行打印。形成面向对象模式一部分的特征有很多。这些特征将在下一章节中进行解释。
The code includes class attribute and instance attributes, which are printed as per the requirement of the output. There are various features that form part of the object oriented pattern. The features are explained in the next chapter.