# 多态和封装

## 多态

```>>> "This is a book".count("s")
2
>>> [1,2,4,3,5,3].count(3)
2```

`>>> f = lambda x,y:x+y`

```>>> f(2,3)
5
>>> f("qiw","sir")
'qiwsir'
>>> f(["python","java"],["c++","lisp"])
['python', 'java', 'c++', 'lisp']```

```>>> f("qiw", 2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
TypeError: cannot concatenate 'str' and 'int' objects```

“多态”，英文是:Polymorphism，在台湾被称作“多型”。维基百科中对此有详细解释说明。

```>>> repr([1,2,3])
'[1, 2, 3]'
>>> repr(1)
'1'
>>> repr({"lang":"python"})
"{'lang': 'Python'}"```

```>>> def length(x):
...     print "The length of", repr(x), "is", len(x)
...

>>> length("how are you")
The length of 'how are you' is 11
>>> length([1,2,3])
The length of [1, 2, 3] is 3
>>> length({"lang":"python","book":"itdiffer.com"})
The length of {'lang': 'python', 'book': 'itdiffer.com'} is 2```

```>>> length(7)
The length of 7 is
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in length
TypeError: object of type 'int' has no len()```

```#!/usr/bin/env Python
# coding=utf-8

"the code is from: http://zetcode.com/lang/python/oop/"

__metaclass__ = type

class Animal:
def __init__(self, name=""):
self.name = name

def talk(self):
pass

class Cat(Animal):
def talk(self):
print "Meow!"

class Dog(Animal):
def talk(self):
print "Woof!"

a = Animal()
a.talk()

c = Cat("Missy")
c.talk()

d = Dog("Rocky")
d.talk()```

```\$ python 21101.py
Meow!
Woof!```

## 封装和私有化

“封装”，是不是把代码写到某个东西里面，“人”在编辑器中打开，就看不到了呢？除非是你的显示器坏了。

Python 中私有化的方法也比较简单，就是在准备私有化的属性（包括方法、数据）名字前面加双下划线。例如：

```#!/usr/bin/env Python
# coding=utf-8

__metaclass__ = type

class ProtectMe:
def __init__(self):
self.me = "qiwsir"
self.__name = "kivi"

def __python(self):
print "I love Python."

def code(self):
print "Which language do you like?"
self.__python()

if __name__ == "__main__":
p = ProtectMe()
print p.me
print p.__name```

```\$ python 21102.py
qiwsir
Traceback (most recent call last):
File "21102.py", line 21, in <module>
print p.__name
AttributeError: 'ProtectMe' object has no attribute '__name'```

```if __name__ == "__main__":
p = ProtectMe()
p.code()
p.__python()```

```\$ python 21102.py
Which language do you like?
I love Python.
Traceback (most recent call last):
File "21102.py", line 23, in <module>
p.__python()
AttributeError: 'ProtectMe' object has no attribute '__python'```

```#!/usr/bin/env Python
# coding=utf-8

__metaclass__ = type

class ProtectMe:
def __init__(self):
self.me = "qiwsir"
self.__name = "kivi"

@property
def name(self):
return self.__name

if __name__ == "__main__":
p = ProtectMe()
print p.name```

```\$ python 21102.py
kivi```