面向?qū)ο蟮哪J绞亲畛S玫哪J健?幾乎所有的編程語(yǔ)言都可以找到這種模式。
下面讓我們看看如何實(shí)現(xiàn)面向?qū)ο蟮哪J?。參考以下?shí)現(xiàn)代碼 -
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))
執(zhí)行上面示例代碼,得到以下輸出結(jié)果 -
說(shuō)明
代碼包括類(lèi)屬性和實(shí)例屬性,它們按照輸出的要求打印。有各種功能構(gòu)成面向?qū)ο竽J降囊徊糠帧?這些功能在下一章中介紹。