Python網(wǎng)絡編程
TCP面向連接的通信方式,UDP與TCP不同,與虛擬電路完全相反,是數(shù)據(jù)報型的無連接套接字。
TCP通信,要先開服務器,后開客戶端。
# tcp sock
tcpSerSock = socket(AF_INET,SOCK_STREAM)
# udp sock
udpSerSock = socket(AF_INET,SOCK_DGRAM)
python apply()函數(shù)
apply(func [, args [, kwargs ]]) 函數(shù)用于當函數(shù)參數(shù)已經(jīng)存在于一個元組或字典中時,間接地調(diào)用函數(shù)。args是一個包含將要提供給函數(shù)的按位置傳遞的參數(shù)的元組。如果省略了args,任 何參數(shù)都不會被傳遞,kwargs是一個包含關鍵字參數(shù)的字典。
apply()的返回值就是func()的返回值,apply()的元素參數(shù)是有序的,元素的順序必須和func()形式參數(shù)的順序一致
下面給幾個例子來詳細的說下:
1、假設是執(zhí)行沒有帶參數(shù)的方法
def say():
print 'say in'
apply(say)
輸出的結果是'say in'
2、函數(shù)只帶元組的參數(shù)。
def say(a, b):
print a, b
apply(say,("hello", "老王python"))
輸出的結果是hello,老王python
_call_函數(shù)
Python中有一個有趣的語法,只要定義類型的時候,實現(xiàn)_call_函數(shù),這個類型就成為可調(diào)用的。換句話說,我們可以把這個類型的對象當作函數(shù)來使用,相當于 重載了括號運算符。
class g_dpm(object):
def __init__(self, g):
self.g = g
def __call__(self, t):
return (self.g*t**2)/2
計算地球場景的時候,我們就可以令e_dpm = g_dpm(9.8),s = e_dpm(t)。
class Animal(object):
def __init__(self, name, legs):
self.name = name
self.legs = legs
self.stomach = []
def __call__(self,food):
self.stomach.append(food)
def poop(self):
if len(self.stomach) > 0:
return self.stomach.pop(0)
def __str__(self):
return 'A animal named %s' % (self.name)
cow = Animal('king', 4) #We make a cow
dog = Animal('flopp', 4) #We can make many animals
print 'We have 2 animales a cow name %s and dog named %s,both have %s legs' % (cow.name, dog.name, cow.legs)
print cow #here __str__ metod work
#We give food to cow
cow('gras')
print cow.stomach
#We give food to dog
dog('bone')
dog('beef')
print dog.stomach
#What comes inn most come out
print cow.poop()
print cow.stomach #Empty stomach
'''''-->output
We have 2 animales a cow name king and dog named flopp,both have 4 legs
A animal named king
['gras']
['bone', 'beef']
gras
[]
'''