中企动力 > 头条 > python中get

网站性能检测评分

注:本网站页面html检测工具扫描网站中存在的基本问题,仅供参考。

python中get

Python网络编程,你get了吗? 营销视频课程

img

童夏蓉

关注

talk is cheap, show you the code.

服务端

完整代码如下:

#!/usr/bin/python# -*- coding: UTF-8 -*-# 文件名:server.pyimport socket # 导入 socket 模块s = socket.socket() # 创建 socket 对象host = socket.gethostname() # 获取本地主机名port = 12345 # 设置端口s.bind((host, port)) # 绑定端口s.listen(5) # 等待客户端连接while True: c, addr = s.accept() # 建立客户端连接。 print '连接地址:', addr c.send('欢迎访问菜鸟教程!') c.close() # 关闭连接

注释:

socket.accept()的返回值是一个元组(conn,address),

c, addr = s.accept() 中的c接收conn,addr接收address;

客户端

完整代码如下:

#!/usr/bin/python# -*- coding: UTF-8 -*-# 文件名:client.pyimport socket # 导入 socket 模块s = socket.socket() # 创建 socket 对象host = socket.gethostname() # 获取本地主机名port = 12345 # 设置端口好s.connect((host, port))print s.recv(1024)s.close()

server.py

现在我们打开两个终端,第一个终端执行 server.py 文件:

$ python server.py

client.py

第二个终端执行 client.py 文件:

$ python client.py欢迎访问菜鸟教程!

server result

这是我们再打开第一个终端,就会看到有以下信息输出:

连接地址: ('192.168.0.118', 62461)

Python基础学习-10:字典的实战1 营销视频课程

img

冷瞳

关注

一、字典的创建:

1.1直接创建字典:

1.2通过dict创建字典:

注意:

dict(variable):variable必须是集合类型的实数或变量,即元组类型、list类型、字典类型;

variable中的元素必须是集合类型的,并且元素的值的个数必须是2;

1.3通过关键字创建字典

1.4 fromkey(seq[,val])函数:创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值;

注意:

fromkeys(variable):variable不能为数字类型;

fromkeys(variable[,value]):value为给定的键的值,不填的情况下默认对应值为None;

二、clear()函数

注意:

clear()是一个原地操作的方法,它是把元素给置空,但其指向的内存地址不会发生变化;

三、copy()函数

返回一个具有相同键值的新字典;

四、get(key[,default=None])函数:访问字典成员

注意:

get()可以访问字典中不存在的键,返回值为None,或者设置的值;

五、detdefault(key[,default=None]):与get()类似,只是如果key不存在于字典中时,将会添加键并将值设为default。

六、keys():以列表的形式返回字典所有的键

七、dict1.update(dict2):将dict2的键值同步到dict1中

八、pop(key)函数和popitem()函数

pop(key):删除字典中key键对应的值,返回值为被删除的值。key必须是字典中存在的键;

popitem():随机删除并返回字典中的一对键值(一般删除末尾对);

如何在 Python 中正确的代理对象 企业视频课程

img

Welcome

关注

本文基于 Python 3.6

题外话

先来看一个问题: 已知对于一个对象来说,运算符 > 会去调用对象的 __gt__ 方法:

已知对于对象来说,__getattribute__ 在寻找实例属性时被无条件调用:

那么根据亚里士多德的三段论来说,我们可以使用一个 override __getattribute__ 方法的对象去代理对象 t 的所有方法,实现一个简单的对象代理:

好像的确可行,但是

重新整理一下思路,> 对去调用对象的 __gt__ 方法,而 __getattribute__ 会去截获属性寻找的过程,返回 t 对象的 __gt__ 方法,所以这种问题应该是前提出现了偏差

根据错误信息可以知道 __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).

正题

那么如何正确地实现一个对象的代理呢?其实 __getattribute__ 也可以,不过要在 Proxy 类中也显示的定义 __gt__ 等 special method。但是 __getattribute__ 在编程时要极为留意,避免 maximum recursion depth exceeded,还是 __getattr__ 更加 friendly

Celery 源代码中有一个现成的实现(她自己声称是 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

另外说一点,使用 _default_cls_attr 而不用 property 装饰器 可以参考 issue 1087

从 class 访问 property 会返回 property 的实例

原因貌似好像是这个 (依据等价实现)

所以 Celery 自己搞了一个 descriptor

喜欢的话关注收藏评论转发比心么么哒!Python学习交流群330637182内有大量的项目开发和新手教学视频五千人大群等着你来加入

Python网络编程,你get了吗? 互联网视频课程

img

沛岚

关注

talk is cheap, show you the code.

服务端

完整代码如下:

#!/usr/bin/python# -*- coding: UTF-8 -*-# 文件名:server.pyimport socket # 导入 socket 模块s = socket.socket() # 创建 socket 对象host = socket.gethostname() # 获取本地主机名port = 12345 # 设置端口s.bind((host, port)) # 绑定端口s.listen(5) # 等待客户端连接while True: c, addr = s.accept() # 建立客户端连接。 print '连接地址:', addr c.send('欢迎访问菜鸟教程!') c.close() # 关闭连接

注释:

socket.accept()的返回值是一个元组(conn,address),

c, addr = s.accept() 中的c接收conn,addr接收address;

客户端

完整代码如下:

#!/usr/bin/python# -*- coding: UTF-8 -*-# 文件名:client.pyimport socket # 导入 socket 模块s = socket.socket() # 创建 socket 对象host = socket.gethostname() # 获取本地主机名port = 12345 # 设置端口好s.connect((host, port))print s.recv(1024)s.close()

server.py

现在我们打开两个终端,第一个终端执行 server.py 文件:

$ python server.py

client.py

第二个终端执行 client.py 文件:

$ python client.py欢迎访问菜鸟教程!

server result

这是我们再打开第一个终端,就会看到有以下信息输出:

连接地址: ('192.168.0.118', 62461)

如何在 Python 中正确的代理对象 公司视频课程

img

书瑶

关注

本文基于 Python 3.6

题外话

先来看一个问题: 已知对于一个对象来说,运算符 > 会去调用对象的 __gt__ 方法:

已知对于对象来说,__getattribute__ 在寻找实例属性时被无条件调用:

那么根据亚里士多德的三段论来说,我们可以使用一个 override __getattribute__ 方法的对象去代理对象 t 的所有方法,实现一个简单的对象代理:

好像的确可行,但是

重新整理一下思路,> 对去调用对象的 __gt__ 方法,而 __getattribute__ 会去截获属性寻找的过程,返回 t 对象的 __gt__ 方法,所以这种问题应该是前提出现了偏差

根据错误信息可以知道 __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).

正题

那么如何正确地实现一个对象的代理呢?其实 __getattribute__ 也可以,不过要在 Proxy 类中也显示的定义 __gt__ 等 special method。但是 __getattribute__ 在编程时要极为留意,避免 maximum recursion depth exceeded,还是 __getattr__ 更加 friendly

Celery 源代码中有一个现成的实现(她自己声称是 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

另外说一点,使用 _default_cls_attr 而不用 property 装饰器 可以参考 issue 1087

从 class 访问 property 会返回 property 的实例

原因貌似好像是这个 (依据等价实现)

所以 Celery 自己搞了一个 descriptor

喜欢的话关注收藏评论转发比心么么哒!Python学习交流群330637182内有大量的项目开发和新手教学视频五千人大群等着你来加入

img

在线咨询

建站在线咨询

img

微信咨询

扫一扫添加
动力姐姐微信

img
img

TOP