多態(tài)和封裝

鴨子類型
多態(tài)
多態(tài):指允許不同類的對象對同一消息做出響應(yīng)。即同一消息可以根據(jù)發(fā)送對象不同而采用多種不同的行為方式

python中的多態(tài)

java中的多態(tài)
python中傳參,不需要檢查參數(shù)的類型,python天生帶多態(tài)屬性
封裝
封裝:將某部分隱藏,在代碼塊外部不能調(diào)用
- 實(shí)現(xiàn)封裝的方法:對屬性和方法的“私有化”命名,即以雙下劃線作為名稱的開始
class Foo:
... __name = 'su'
... book = 'python'
... def get_name(self):
... return Foo.__name
...
f = Foo()
dir(f)
['_Foo__name', 'class', 'delattr', 'dict', 'dir', 'doc', 'eq', 'format', 'ge', 'getattribute', 'gt', 'hash', 'init', 'init_subclass', 'le', 'lt', 'module', 'ne', 'new', 'reduce', 'reduce_ex', 'repr', 'setattr', 'sizeof', 'str', 'subclasshook', 'weakref', 'book', 'get_name']
f.book
'python'
f.__name
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Foo' object has no attribute '__name'
f.get_name()
'su'