網(wǎng)站性能檢測評(píng)分
注:本網(wǎng)站頁面html檢測工具掃描網(wǎng)站中存在的基本問題,僅供參考。
python中g(shù)et
Python網(wǎng)絡(luò)編程,你get了嗎? 互聯(lián)網(wǎng)視頻課程
talk is cheap, show you the code.
服務(wù)端
完整代碼如下:
#!/usr/bin/python# -*- coding: UTF-8 -*-# 文件名:server.pyimport socket # 導(dǎo)入 socket 模塊s = socket.socket() # 創(chuàng)建 socket 對(duì)象host = socket.gethostname() # 獲取本地主機(jī)名port = 12345 # 設(shè)置端口s.bind((host, port)) # 綁定端口s.listen(5) # 等待客戶端連接while True: c, addr = s.accept() # 建立客戶端連接。 print '連接地址:', addr c.send('歡迎訪問菜鳥教程!') c.close() # 關(guān)閉連接
注釋:
socket.accept()的返回值是一個(gè)元組(conn,address),
c, addr = s.accept() 中的c接收conn,addr接收address;
客戶端
完整代碼如下:
#!/usr/bin/python# -*- coding: UTF-8 -*-# 文件名:client.pyimport socket # 導(dǎo)入 socket 模塊s = socket.socket() # 創(chuàng)建 socket 對(duì)象host = socket.gethostname() # 獲取本地主機(jī)名port = 12345 # 設(shè)置端口好s.connect((host, port))print s.recv(1024)s.close()
server.py
現(xiàn)在我們打開兩個(gè)終端,第一個(gè)終端執(zhí)行 server.py 文件:
$ python server.py
client.py
第二個(gè)終端執(zhí)行 client.py 文件:
$ python client.py歡迎訪問菜鳥教程!
server result
這是我們再打開第一個(gè)終端,就會(huì)看到有以下信息輸出:
連接地址: ('192.168.0.118', 62461)
Python基礎(chǔ)學(xué)習(xí)-10:字典的實(shí)戰(zhàn)1 推廣視頻課程
一、字典的創(chuàng)建:
1.1直接創(chuàng)建字典:
1.2通過dict創(chuàng)建字典:
注意:
dict(variable):variable必須是集合類型的實(shí)數(shù)或變量,即元組類型、list類型、字典類型;
variable中的元素必須是集合類型的,并且元素的值的個(gè)數(shù)必須是2;
1.3通過關(guān)鍵字創(chuàng)建字典
1.4 fromkey(seq[,val])函數(shù):創(chuàng)建一個(gè)新字典,以序列seq中元素做字典的鍵,val為字典所有鍵對(duì)應(yīng)的初始值;
注意:
fromkeys(variable):variable不能為數(shù)字類型;
fromkeys(variable[,value]):value為給定的鍵的值,不填的情況下默認(rèn)對(duì)應(yīng)值為None;
二、clear()函數(shù)
注意:
clear()是一個(gè)原地操作的方法,它是把元素給置空,但其指向的內(nèi)存地址不會(huì)發(fā)生變化;
三、copy()函數(shù)
返回一個(gè)具有相同鍵值的新字典;
四、get(key[,default=None])函數(shù):訪問字典成員
注意:
get()可以訪問字典中不存在的鍵,返回值為None,或者設(shè)置的值;
五、detdefault(key[,default=None]):與get()類似,只是如果key不存在于字典中時(shí),將會(huì)添加鍵并將值設(shè)為default。
六、keys():以列表的形式返回字典所有的鍵
七、dict1.update(dict2):將dict2的鍵值同步到dict1中
八、pop(key)函數(shù)和popitem()函數(shù)
pop(key):刪除字典中key鍵對(duì)應(yīng)的值,返回值為被刪除的值。key必須是字典中存在的鍵;
popitem():隨機(jī)刪除并返回字典中的一對(duì)鍵值(一般刪除末尾對(duì));
如何在 Python 中正確的代理對(duì)象 公司視頻課程
本文基于 Python 3.6
題外話
先來看一個(gè)問題: 已知對(duì)于一個(gè)對(duì)象來說,運(yùn)算符 > 會(huì)去調(diào)用對(duì)象的 __gt__ 方法:
已知對(duì)于對(duì)象來說,__getattribute__ 在尋找實(shí)例屬性時(shí)被無條件調(diào)用:
那么根據(jù)亞里士多德的三段論來說,我們可以使用一個(gè) override __getattribute__ 方法的對(duì)象去代理對(duì)象 t 的所有方法,實(shí)現(xiàn)一個(gè)簡單的對(duì)象代理:
好像的確可行,但是
重新整理一下思路,> 對(duì)去調(diào)用對(duì)象的 __gt__ 方法,而 __getattribute__ 會(huì)去截獲屬性尋找的過程,返回 t 對(duì)象的 __gt__ 方法,所以這種問題應(yīng)該是前提出現(xiàn)了偏差
根據(jù)錯(cuò)誤信息可以知道 __getattribute__ 沒起作用,翻閱文檔可知
Called unconditionally to implement attribute accesses for instances of the class. If the class also defines __getattr__(), the latter will not be called unless __getattribute__() either calls it explicitly or raises an AttributeError. This method should return the (computed) attribute value or raise an AttributeError exception. In order to avoid infinite recursion in this method, its implementation should always call the base class method with the same name to access any attributes it needs, for example, object.__getattribute__(self, name).
正題
那么如何正確地實(shí)現(xiàn)一個(gè)對(duì)象的代理呢?其實(shí) __getattribute__ 也可以,不過要在 Proxy 類中也顯示的定義 __gt__ 等 special method。但是 __getattribute__ 在編程時(shí)要極為留意,避免 maximum recursion depth exceeded,還是 __getattr__ 更加 friendly
Celery 源代碼中有一個(gè)現(xiàn)成的實(shí)現(xiàn)(她自己聲稱是 stolen from werkzeug.local.Proxy)
def _default_cls_attr(name, type_, cls_value):
# Proxy uses properties to forward the standard
# class attributes __module__, __name__ and __doc__ to the real
# object, but these needs to be a string when accessed from
# the Proxy class directly. This is a hack to make that work.
# -- See Issue #1087.
def __new__(cls, getter):
instance = type_.__new__(cls, cls_value)
instance.__getter = getter
return instance
def __get__(self, obj, cls=None):
return self.__getter(obj) if obj is not None else self
return type(bytes_if_py2(name), (type_,), {
'__new__': __new__, '__get__': __get__,
})
class Proxy(object):
"""Proxy to another object."""
# Code stolen from werkzeug.local.Proxy.
__slots__ = ('__local', '__args', '__kwargs', '__dict__')
def __init__(self, local,
args=None, kwargs=None, name=None, __doc__=None):
object.__setattr__(self, '_Proxy__local', local)
object.__setattr__(self, '_Proxy__args', args or ())
object.__setattr__(self, '_Proxy__kwargs', kwargs or {})
if name is not None:
object.__setattr__(self, '__custom_name__', name)
if __doc__ is not None:
object.__setattr__(self, '__doc__', __doc__)
@_default_cls_attr('name', str, __name__)
def __name__(self):
try:
return self.__custom_name__
except AttributeError:
return self._get_current_object().__name__
@_default_cls_attr('qualname', str, __name__)
def __qualname__(self):
return self._get_current_object().__qualname__
@_default_cls_attr('module', str, __module__)
def __module__(self):
return self._get_current_object().__module__
@_default_cls_attr('doc', str, __doc__)
def __doc__(self):
return self._get_current_object().__doc__
def _get_class(self):
return self._get_current_object().__class__
@property
def __class__(self):
return self._get_class()
def _get_current_object(self):
"""Get current object.
This is useful if you want the real
object behind the proxy at a time for performance reasons or because
you want to pass the object into a different context.
"""
loc = object.__getattribute__(self, '_Proxy__local')
if not hasattr(loc, '__release_local__'):
return loc(*self.__args, **self.__kwargs)
try: # pragma: no cover
# not sure what this is about
return getattr(loc, self.__name__)
except AttributeError: # pragma: no cover
raise RuntimeError('no object bound to {0.__name__}'.format(self))
def __dict__(self):
return self._get_current_object().__dict__
except RuntimeError: # pragma: no cover
raise AttributeError('__dict__')
def __repr__(self):
obj = self._get_current_object()
return '<{0} unbound>'.format(self.__class__.__name__)
return repr(obj)
def __bool__(self):
return bool(self._get_current_object())
return False
__nonzero__ = __bool__ # Py2
def __dir__(self):
return dir(self._get_current_object())
return []
def __getattr__(self, name):
if name == '__members__':
return getattr(self._get_current_object(), name)
def __setitem__(self, key, value):
self._get_current_object()[key] = value
def __delitem__(self, key):
del self._get_current_object()[key]
def __setslice__(self, i, j, seq):
self._get_current_object()[i:j] = seq
def __delslice__(self, i, j):
del self._get_current_object()[i:j]
def __setattr__(self, name, value):
setattr(self._get_current_object(), name, value)
def __delattr__(self, name):
delattr(self._get_current_object(), name)
def __str__(self):
return str(self._get_current_object())
def __lt__(self, other):
return self._get_current_object() < other
def __le__(self, other):
return self._get_current_object() <= other
# omit some special method
另外說一點(diǎn),使用 _default_cls_attr 而不用 property 裝飾器 可以參考 issue 1087
從 class 訪問 property 會(huì)返回 property 的實(shí)例
原因貌似好像是這個(gè) (依據(jù)等價(jià)實(shí)現(xiàn))
所以 Celery 自己搞了一個(gè) descriptor
喜歡的話關(guān)注收藏評(píng)論轉(zhuǎn)發(fā)比心么么噠!Python學(xué)習(xí)交流群330637182內(nèi)有大量的項(xiàng)目開發(fā)和新手教學(xué)視頻五千人大群等著你來加入
Python網(wǎng)絡(luò)編程,你get了嗎? 企業(yè)視頻課程
talk is cheap, show you the code.
服務(wù)端
完整代碼如下:
#!/usr/bin/python# -*- coding: UTF-8 -*-# 文件名:server.pyimport socket # 導(dǎo)入 socket 模塊s = socket.socket() # 創(chuàng)建 socket 對(duì)象host = socket.gethostname() # 獲取本地主機(jī)名port = 12345 # 設(shè)置端口s.bind((host, port)) # 綁定端口s.listen(5) # 等待客戶端連接while True: c, addr = s.accept() # 建立客戶端連接。 print '連接地址:', addr c.send('歡迎訪問菜鳥教程!') c.close() # 關(guān)閉連接
注釋:
socket.accept()的返回值是一個(gè)元組(conn,address),
c, addr = s.accept() 中的c接收conn,addr接收address;
客戶端
完整代碼如下:
#!/usr/bin/python# -*- coding: UTF-8 -*-# 文件名:client.pyimport socket # 導(dǎo)入 socket 模塊s = socket.socket() # 創(chuàng)建 socket 對(duì)象host = socket.gethostname() # 獲取本地主機(jī)名port = 12345 # 設(shè)置端口好s.connect((host, port))print s.recv(1024)s.close()
server.py
現(xiàn)在我們打開兩個(gè)終端,第一個(gè)終端執(zhí)行 server.py 文件:
$ python server.py
client.py
第二個(gè)終端執(zhí)行 client.py 文件:
$ python client.py歡迎訪問菜鳥教程!
server result
這是我們再打開第一個(gè)終端,就會(huì)看到有以下信息輸出:
連接地址: ('192.168.0.118', 62461)
如何在 Python 中正確的代理對(duì)象 企業(yè)視頻課程
本文基于 Python 3.6
題外話
先來看一個(gè)問題: 已知對(duì)于一個(gè)對(duì)象來說,運(yùn)算符 > 會(huì)去調(diào)用對(duì)象的 __gt__ 方法:
已知對(duì)于對(duì)象來說,__getattribute__ 在尋找實(shí)例屬性時(shí)被無條件調(diào)用:
那么根據(jù)亞里士多德的三段論來說,我們可以使用一個(gè) override __getattribute__ 方法的對(duì)象去代理對(duì)象 t 的所有方法,實(shí)現(xiàn)一個(gè)簡單的對(duì)象代理:
好像的確可行,但是
重新整理一下思路,> 對(duì)去調(diào)用對(duì)象的 __gt__ 方法,而 __getattribute__ 會(huì)去截獲屬性尋找的過程,返回 t 對(duì)象的 __gt__ 方法,所以這種問題應(yīng)該是前提出現(xiàn)了偏差
根據(jù)錯(cuò)誤信息可以知道 __getattribute__ 沒起作用,翻閱文檔可知
Called unconditionally to implement attribute accesses for instances of the class. If the class also defines __getattr__(), the latter will not be called unless __getattribute__() either calls it explicitly or raises an AttributeError. This method should return the (computed) attribute value or raise an AttributeError exception. In order to avoid infinite recursion in this method, its implementation should always call the base class method with the same name to access any attributes it needs, for example, object.__getattribute__(self, name).
正題
那么如何正確地實(shí)現(xiàn)一個(gè)對(duì)象的代理呢?其實(shí) __getattribute__ 也可以,不過要在 Proxy 類中也顯示的定義 __gt__ 等 special method。但是 __getattribute__ 在編程時(shí)要極為留意,避免 maximum recursion depth exceeded,還是 __getattr__ 更加 friendly
Celery 源代碼中有一個(gè)現(xiàn)成的實(shí)現(xiàn)(她自己聲稱是 stolen from werkzeug.local.Proxy)
def _default_cls_attr(name, type_, cls_value):
# Proxy uses properties to forward the standard
# class attributes __module__, __name__ and __doc__ to the real
# object, but these needs to be a string when accessed from
# the Proxy class directly. This is a hack to make that work.
# -- See Issue #1087.
def __new__(cls, getter):
instance = type_.__new__(cls, cls_value)
instance.__getter = getter
return instance
def __get__(self, obj, cls=None):
return self.__getter(obj) if obj is not None else self
return type(bytes_if_py2(name), (type_,), {
'__new__': __new__, '__get__': __get__,
})
class Proxy(object):
"""Proxy to another object."""
# Code stolen from werkzeug.local.Proxy.
__slots__ = ('__local', '__args', '__kwargs', '__dict__')
def __init__(self, local,
args=None, kwargs=None, name=None, __doc__=None):
object.__setattr__(self, '_Proxy__local', local)
object.__setattr__(self, '_Proxy__args', args or ())
object.__setattr__(self, '_Proxy__kwargs', kwargs or {})
if name is not None:
object.__setattr__(self, '__custom_name__', name)
if __doc__ is not None:
object.__setattr__(self, '__doc__', __doc__)
@_default_cls_attr('name', str, __name__)
def __name__(self):
try:
return self.__custom_name__
except AttributeError:
return self._get_current_object().__name__
@_default_cls_attr('qualname', str, __name__)
def __qualname__(self):
return self._get_current_object().__qualname__
@_default_cls_attr('module', str, __module__)
def __module__(self):
return self._get_current_object().__module__
@_default_cls_attr('doc', str, __doc__)
def __doc__(self):
return self._get_current_object().__doc__
def _get_class(self):
return self._get_current_object().__class__
@property
def __class__(self):
return self._get_class()
def _get_current_object(self):
"""Get current object.
This is useful if you want the real
object behind the proxy at a time for performance reasons or because
you want to pass the object into a different context.
"""
loc = object.__getattribute__(self, '_Proxy__local')
if not hasattr(loc, '__release_local__'):
return loc(*self.__args, **self.__kwargs)
try: # pragma: no cover
# not sure what this is about
return getattr(loc, self.__name__)
except AttributeError: # pragma: no cover
raise RuntimeError('no object bound to {0.__name__}'.format(self))
def __dict__(self):
return self._get_current_object().__dict__
except RuntimeError: # pragma: no cover
raise AttributeError('__dict__')
def __repr__(self):
obj = self._get_current_object()
return '<{0} unbound>'.format(self.__class__.__name__)
return repr(obj)
def __bool__(self):
return bool(self._get_current_object())
return False
__nonzero__ = __bool__ # Py2
def __dir__(self):
return dir(self._get_current_object())
return []
def __getattr__(self, name):
if name == '__members__':
return getattr(self._get_current_object(), name)
def __setitem__(self, key, value):
self._get_current_object()[key] = value
def __delitem__(self, key):
del self._get_current_object()[key]
def __setslice__(self, i, j, seq):
self._get_current_object()[i:j] = seq
def __delslice__(self, i, j):
del self._get_current_object()[i:j]
def __setattr__(self, name, value):
setattr(self._get_current_object(), name, value)
def __delattr__(self, name):
delattr(self._get_current_object(), name)
def __str__(self):
return str(self._get_current_object())
def __lt__(self, other):
return self._get_current_object() < other
def __le__(self, other):
return self._get_current_object() <= other
# omit some special method
另外說一點(diǎn),使用 _default_cls_attr 而不用 property 裝飾器 可以參考 issue 1087
從 class 訪問 property 會(huì)返回 property 的實(shí)例
原因貌似好像是這個(gè) (依據(jù)等價(jià)實(shí)現(xiàn))
所以 Celery 自己搞了一個(gè) descriptor
喜歡的話關(guān)注收藏評(píng)論轉(zhuǎn)發(fā)比心么么噠!Python學(xué)習(xí)交流群330637182內(nèi)有大量的項(xiàng)目開發(fā)和新手教學(xué)視頻五千人大群等著你來加入