今天开始进入python的对象世界。
class Header(object):
'''A SIP header object with dynamic properties.
Attributes such as name, and various parameters can be accessed on the object.
>>> print repr(Header('"Kundan Singh" <sip:kundan@example.net>', 'To'))
To: "Kundan Singh" <sip:kundan@example.net>
>>> print repr(Header('"Kundan"<sip:kundan99@example.net>', 'To'))
To: "Kundan" <sip:kundan99@example.net>
>>> print repr(Header('Sanjay <sip:sanjayc77@example.net>', 'fRoM'))
From: "Sanjay" <sip:sanjayc77@example.net>
>>> print repr(Header('application/sdp', 'conTenT-tyPe'))
Content-Type: application/sdp
>>> print repr(Header('presence; param=value;param2=another', 'Event'))
Event: presence;param=value;param2=another
>>> print repr(Header('78 INVITE', 'CSeq'))
CSeq: 78 INVITE
'''
以上代码定义了一个类Header。
def __init__(self, value=None, name=None):
'''Construct a Header from optional value and optional name.'''
self.name = name and _canon(name.strip()) or None
self.value = self._parse(value.strip(), self.name and self.name.lower()
__init__函数类似C++的构造函数,在创建对象时会自动调用。类的成员函数第一个参数必须是self, 类似C++的this指针,但this指针并不需要显式指定。
成员函数的参数可以指定默认参数,"None"是python定义的表示空的对象。
在类和成员函数定义下面出现的三引号会自动文档化,比如下面的例子:
>>> class C():
"""class C"""
def mf():
"""C::mf"""
return
>>> help(C)
Help on class C in module __main__:
class C
| class C
|
| Methods defined here:
|
| mf()
| C::mf
>>> print(C.__doc__)
class C
>>> print(C.mf.__doc__)
C::mf
>>>