面向对象的模式是最常用的模式.这种模式几乎可以在每种编程语言中找到.
如何实现面向对象的模式?
现在让我们看看如何实现对象导向模式.
class Parrot: # class attribute species = "bird" # instance attribute def __init__(self, name, age): self.name = name self.age = age# instantiate the Parrot classblu = Parrot("Blu", 10)woo = Parrot("Woo", 15)# access the class attributesprint("Blu is a {}".format(blu.__class__.species))print("Woo is also a {}".format(woo.__class__.species))# access the instance attributesprint("{} is {} years old".format( blu.name, blu.age))print("{} is {} years old".format( woo.name, woo.age))
输出
上述程序生成以下输出
解释
代码包括类属性和实例属性,按照要求打印输出.有各种特征构成面向对象模式的一部分.这些功能将在下一章中解释.