python - hashable 的瘦代理类

标签 python proxy-classes

我需要某种薄包装对象来标记字典键,例如:

d = {
  Required('name'): str,
  Optional('age'): int,
}

这些包装器的行为应该与包装对象类似(比较、散列等):

marked = Required('name')
marked == 'name'  #-> True
d[marked] = 'hello'
d['name']  #-> 'hello'

有一个附加属性:它应该记住添加的类:

isinstance(marked, Required)  #-> True

并且添加的类应该具有自定义方法。

这实际上类似于可哈希对象上的 mixin。


我不喜欢那些重量级的Proxy Patterns它模仿所有特殊属性并思考以下想法:

class Wrapper(object):
    def __new__(cls, value):
        value_type = type(value)
        Type = type(
            value_type.__name__,  # same name
            (cls, value_type),  # Wrapper + bases
            {})
        Type.__new__ = value_type.__new__  # prevent recursion
        return Type(value)

    # Override method
    def __repr__(self):
        return 'Wrapper({})'.format(self)

更好的想法?

最佳答案

你的Wrapper类可以工作,是的。但是,如果您想要的只是一个包装器来充当具有额外方法的替代键,那么我只需创建一个专用类即可。 这里显式优于隐式

此类只需代理 __eq____hash__方法:

class HashableProxy(object):
    def __init__(self, wrapped):
        self._wrapped = wrapped

    def __eq__(self, other):
        return self._wrapped == other

    def __hash__(self):
        return hash(self._wrapped)

class Required(HashableProxy):
    pass

class Optional(HashableProxy):
    pass

您可以根据需要向其中添加方法。

演示:

>>> marked = Required('name')
>>> marked == 'name'
True
>>> d = {}
>>> d[marked] = 'hello'
>>> d['name']
'hello'
>>> isinstance(marked, Required)
True

关于python - hashable 的瘦代理类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25510668/

相关文章:

python - kernprof.py : NameError: name 'profile' is not defined

python - 什么时候在 Python 的函数定义中需要 * 字符?

python - 基本的 Python BeautifulSoup 网络抓取 Tripadvisor 评论和数据清理

python - 在散点图中,在 matplotlib 中围绕数据点绘制平滑多边形

java - 如何从动态代理中解包原始对象

python - Python 3.4 和阅读这个简单的 XML 站点有什么关系?

c# - 使用延迟加载的 NHibernate ObjectProxy 转换

java - Java 中的代理有什么用?

java - 如果被 Spring 包装到代理中,如何知道原始类名?

c# - Web 服务不处理来自具有代理类的同一应用程序的多个同时请求