【问题标题】:Wrapping Python int/float objects包装 Python int/float 对象
【发布时间】:2011-03-09 23:02:53
【问题描述】:

我正在开发一个 Python 并发框架(我知道,YACF)并希望能够将变量作为 Futures 返回,但用户不会注意到它。

现在我在做:

x = someAsyncMethod(args)
print "Return value is %d" % x.get_value( )

因为该方法返回一个 Future 对象,但我希望它是:

x = someAsyncMethod(args)
print "Return value is %d" % x

但仍然调用了 x 的 .get_value( )。因此,我想代理包装 Python 对象,包括 int。类似于 __get__ 的东西,但是如果 ProxyInt 是 int 的代理并且我做了:

x = ProxyInt(10)
print x

n = x

我的“__get__”方法将被调用并在执行“return 10”之前做一些魔术

【问题讨论】:

  • 仅供参考:我相信__get__ 方法适用于描述符,但它并不能满足您的要求。描述符必须是类的属性...即,您必须通过属性访问该值,__get__ 才能工作。

标签: python concurrency metaprogramming


【解决方案1】:
>>> class I(object):
...   def __int__(self):
...     return 42
... 
>>> i = I()
>>> print '%d' % i
42
>>> class F(object):
...   def __float__(self):
...     return 3.14
... 
>>> f = F()
>>> print '%f' % f
3.140000
>>> class S(object):
...   def __str__(self):
...     return 'foo'
... 
>>> s = S()
>>> print s
foo

【讨论】:

  • 哇,真快。谢谢你。我不知道 __str__ 不太了解表兄弟 __int__ 和 __float__
  • 还有__complex__()。不能忘记那个。
【解决方案2】:

您可以覆盖__getattr____getattribute__(以最适合您需要的套件为准)来执行“魔术”,例如,代理的第一个属性访问。

【讨论】:

  • 覆盖这两个在我的情况下不起作用,因为我需要一个触发器来访问对象本身,而不仅仅是它的属性。 (但我将它们用于框架中的其他事情)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-24
  • 1970-01-01
  • 1970-01-01
  • 2023-04-10
  • 2011-10-11
  • 2011-09-28
相关资源
最近更新 更多