包装对象 [英] Wrapper objects

查看:52
本文介绍了包装对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在Python中创建透明的包装器对象?


我想在包装器类上实现__getattribute__或者

它的元类会执行技巧,但它不适用于运算符中构建的



类Foo(对象):

class __metaclass __(类型):

def __getattribute __(self,name):

print" Klass",name

返回类型.__ getattribute __(self,name )

def __getattribute __(self,name):

print" Objekt",name

return object .__ getattribute __(self,name)

Foo()+ 1
Traceback(最近一次调用最后一次):

文件"< stdin>",第1行,在?

TypeError:不支持的操作数类型+:'''Foo''和''int' 'Foo().__ add __(1)



Objekt __add__

回溯(最近一次调用最后一次):

文件"< stdin>",第1行,在?

文件中;< stdin>",第8行,在__getattribute__

AttributeError:''Foo''对象没有属性''__add__''

因此,请注意+ b不做


试试:

返回.__添加__(b)

除外:

返回b .__ radd __(a)


并且都没有,因为我第一次想到


尝试:

返回类型(a).__添加__(a,b)

....


但是有点像


尝试:

返回类型.__ getattribute __(类型(a),''_ _添加__'')(a,b)

....

所以我天真地实现了一个包装类,

类包装器(对象):

def __init __(self,value,otherdata):

self.value = value

self.otherdata = otherdata

def __getattribute __(self,name):

return getattr(self .va lue,name)

不起作用。解决方案的任何想法?

解决方案

2004年12月9日06:11:41 -0800,Egil M?ller< re **** @ takeit.se>写道:

有没有办法在Python中创建透明的包装器对象?




这项工作 - < http://aspn.activestate .com / ASPN / Cookbook / Python / Recipe / 52295>?

-

干杯,

Simon B,
si***@brunningonline.net
http://www.brunningonline.net/simon/blog/


2004年12月9日06:11:41 -0800, re****@takeit.se (Egil M?ller)写道:

有没有办法在Python中创建透明包装器对象?

我认为在包装器类或其元类上实现__getattribute__会做的伎俩,但它不适用于运算符中构建的
:类Foo(对象):
类__metaclass __(类型):
def __get属性__(self,name):
print" Klass",name
返回类型.__ getattribute __(self,name)
def __getattribute __(self,name):
print" Objekt",名称
返回对象.__ getattribute __(self,name)

Foo()+ 1Traceback(最近一次通话)最后):
文件"< stdin>",第1行,在?
TypeError:不支持的操作数类型为+:'''Foo''和''int''Foo( ).__ add __(1)Objekt __add__
Traceback(最近一次调用最后一次):
文件"< stdin>",第1行,在?
文件"< stdin> ",第8行,在__getattribute__
AttributeError:''Foo''对象没有属性''__add__''

因此,请注意a + b不做

尝试:
返回一个.__添加__(b)
除了:
返回b .__ radd __(a)

并且都没有,正如我第一次想到的那样

尝试:
返回类型(a).__添加__(a,b)
...

但是有点类似于

尝试:
返回类型。 __getattribute __(type(a),''__ add __'')(a,b)
...

所以我的包装类的天真实现,

class wrapper(object):
def __init __(self,value,otherdata):
self.value = value
self.otherdata = otherdata
def __getattribute __(self,name):
返回getattr(self.value,name)

不起作用。解决方案的任何想法?




这似乎有点走向它:

class MethodDesc(object):
... def __get __(self,inst,cls = None):

...如果inst为None:返回自我

... func = self .__ dict __ [''func'']

... if func:return func .__ get __(self.thing,type(self.thing))

... else:return getattr(self.thing,self.name)

... def __init __(self,name,thing,func):

... self.name =姓名

... self.thing = thing

... self.func = func

... def __call __(self, * args,** kw):print''调用%s:%r%r''%(self.name,args,kw)

... def wrapit(thing,* otherdata) :
... class Wrapper(object):

... def __metaclass __(cname,cbases,cdict):

... for name,func in type(thing).__ dict __。items():

... if callable(func):

...如果名字不在[

...''__getattr__'',''__ getattribute__'',''__ setattr__'' ,

...''__ new__'',''__ init__'']:

... cdict [name] = MethodDesc(name,thing,func)

...其他:

... cdict [name] = MethodDesc(名称,东西,无)

...返回类型( cname,cbases,cdict)

... def __init __(self,* otherdata):

... if otherdata:self.otherdata = otherdata

... def __getattr __(self,name):

... raise AttributeError(''Wrapped%r object没有属性%r''%(type(self).__ name__,姓名))

... Wrapper .__ name__ =''Wrapped _''+ type(thing).__ name__

... return Wrapper(* otherdata)

... D级emo(对象):
... a =''eigh''

... two = 2

... def foo(self):返回''演示foo''

... def bar(self,* args,** kw):print''Demo bar%r%r''%(args,kw)

... o2 = wrapit(Demo(),''stuff'')
o2.foo
<绑定方法Demo.foo of< __ main __。演示对象位于0x02EF184C> ;> o2.foo()
''Demo foo''o2.bar(1,2,3,x = 111,y = 222)
演示栏(1,2,3){''y '':222,''x'':111} o2.a
''eigh''o2.two
2 o2.z
Traceback(最近一次调用最后一次):

文件"< stdin>",第1行,在?

文件"< stdin>",第16行,在__getattr__

AttributeError:Wrapped''Wrapped_Demo''对象没有属性''z''o2.z =''zee''
o2.z
''zee''o2
< ; Wrapped_Demo对象位于0x02EF1B6C> o2.a =''不是eigh''
o2.a
''没有eigh''del o2.a
o2.a
''eigh''o3 = wrapit (''奇怪的'',''东西'')
o3
''奇怪''o3.otherdata
(''stuff'',)o3 [2:]
''范围''
o3.z
回溯(最近一次调用最后一次):

文件"< stdin>",第1行,in?

文件"< stdin>",第16行,在__getattr__

AttributeError:Wrapped''Wrapped_str''对象没有属性''z''


没有测试超出你所看到的;-)这没有包装对象的设置属性,

所以设置属性将它们设置在包装器本身,但是可以修复。


现在您想要使用包装器是什么? ;-)

注:

o3 + =''失败''
o3
''strangefail''type(o3)



< type''tr''>


所以如果你想要新的包装实例作为各种结果操作,我们需要更多的代码;-)

另一次...(参见我最近的一篇关于复合作为点类型的文章)。


问候,

Bengt Richter


Simon Brunning写道:

2004年12月9日06:11:41 -0800,Egil M?ller< re **** @ takeit.se>写道:

有没有办法在Python中创建透明的包装器对象?



这项工作 - < http://aspn.activestate .com / ASPN / Cookbook / Python / Recipe / 52295>?




仅适用于旧式课程。如果你从对象或其他内容继承

,则该配方失败。


干杯,

尼克。


-

Nick Coghlan | nc******@email.com |澳大利亚布里斯班

--------------------------------------- ------------------------
http://boredomandlaziness.skystorm.net


Is there any way to create transparent wrapper objects in Python?

I thought implementing __getattribute__ on either the wrapper class or
its metaclass would do the trick, but it does not work for the built
in operators:

class Foo(object):
class __metaclass__(type):
def __getattribute__(self, name):
print "Klass", name
return type.__getattribute__(self, name)
def __getattribute__(self, name):
print "Objekt", name
return object.__getattribute__(self, name)

Foo() + 1 Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: unsupported operand type(s) for +: ''Foo'' and ''int'' Foo().__add__(1)


Objekt __add__
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 8, in __getattribute__
AttributeError: ''Foo'' object has no attribute ''__add__''
Thus, note that a + b does not do

try:
return a.__add__(b)
except:
return b.__radd__(a)

and neither, as I first thought

try:
return type(a).__add__(a, b)
....

but something along the lines of

try:
return type.__getattribute__(type(a), ''__add__'')(a, b)
....
So my naive implementation of a wrapper class,
class wrapper(object):
def __init__(self, value, otherdata):
self.value = value
self.otherdata = otherdata
def __getattribute__(self, name):
return getattr(self.value, name)
does not work. Any ideas for a solution?

解决方案

On 9 Dec 2004 06:11:41 -0800, Egil M?ller <re****@takeit.se> wrote:

Is there any way to create transparent wrapper objects in Python?



This work - <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52295>?

--
Cheers,
Simon B,
si***@brunningonline.net,
http://www.brunningonline.net/simon/blog/


On 9 Dec 2004 06:11:41 -0800, re****@takeit.se (Egil M?ller) wrote:

Is there any way to create transparent wrapper objects in Python?

I thought implementing __getattribute__ on either the wrapper class or
its metaclass would do the trick, but it does not work for the built
in operators:

class Foo(object):
class __metaclass__(type):
def __getattribute__(self, name):
print "Klass", name
return type.__getattribute__(self, name)
def __getattribute__(self, name):
print "Objekt", name
return object.__getattribute__(self, name)

Foo() + 1Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: unsupported operand type(s) for +: ''Foo'' and ''int'' Foo().__add__(1)Objekt __add__
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 8, in __getattribute__
AttributeError: ''Foo'' object has no attribute ''__add__''
Thus, note that a + b does not do

try:
return a.__add__(b)
except:
return b.__radd__(a)

and neither, as I first thought

try:
return type(a).__add__(a, b)
...

but something along the lines of

try:
return type.__getattribute__(type(a), ''__add__'')(a, b)
...
So my naive implementation of a wrapper class,
class wrapper(object):
def __init__(self, value, otherdata):
self.value = value
self.otherdata = otherdata
def __getattribute__(self, name):
return getattr(self.value, name)
does not work. Any ideas for a solution?



This seems to go some way towards it:

class MethodDesc(object): ... def __get__(self, inst, cls=None):
... if inst is None: return self
... func = self.__dict__[''func'']
... if func: return func.__get__(self.thing, type(self.thing))
... else: return getattr(self.thing, self.name)
... def __init__(self, name, thing, func):
... self.name = name
... self.thing = thing
... self.func = func
... def __call__(self, *args, **kw): print ''called %s: %r %r''%(self.name, args, kw)
... def wrapit(thing, *otherdata): ... class Wrapper(object):
... def __metaclass__(cname, cbases, cdict):
... for name, func in type(thing).__dict__.items():
... if callable(func):
... if name not in [
... ''__getattr__'', ''__getattribute__'', ''__setattr__'',
... ''__new__'', ''__init__'']:
... cdict[name] = MethodDesc(name, thing, func)
... else:
... cdict[name] = MethodDesc(name, thing, None)
... return type(cname, cbases, cdict)
... def __init__(self, *otherdata):
... if otherdata: self.otherdata = otherdata
... def __getattr__(self, name):
... raise AttributeError(''Wrapped %r object has no attribute %r''% (type(self).__name__, name))
... Wrapper.__name__ = ''Wrapped_''+type(thing).__name__
... return Wrapper(*otherdata)
... class Demo(object): ... a = ''eigh''
... two = 2
... def foo(self): return ''Demo foo''
... def bar(self, *args, **kw): print ''Demo bar %r %r''%(args, kw)
... o2 = wrapit( Demo(), ''stuff'')
o2.foo <bound method Demo.foo of <__main__.Demo object at 0x02EF184C>> o2.foo() ''Demo foo'' o2.bar(1,2,3,x=111,y=222) Demo bar (1, 2, 3) {''y'': 222, ''x'': 111} o2.a ''eigh'' o2.two 2 o2.z Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 16, in __getattr__
AttributeError: Wrapped ''Wrapped_Demo'' object has no attribute ''z'' o2.z = ''zee''
o2.z ''zee'' o2 <Wrapped_Demo object at 0x02EF1B6C> o2.a = ''not eigh''
o2.a ''not eigh'' del o2.a
o2.a ''eigh'' o3 = wrapit(''strange'', ''stuff'')
o3 ''strange'' o3.otherdata (''stuff'',) o3[2:] ''range''
o3.z Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 16, in __getattr__
AttributeError: Wrapped ''Wrapped_str'' object has no attribute ''z''

Not tested beyond what you see ;-) This doesn''t wrap setting attributes on the wrapped object,
so setting attributes sets them on the wrapper itself, but that could be fixed.

Now what was it you wanted to use a wrapper for? ;-)
Note:
o3 += ''fail''
o3 ''strangefail'' type(o3)


<type ''str''>

So if you want new wrapped instances as results from various ops, we need some more code ;-)
Another time ... (cf. a recent post of mine re wrapping complex as a point type).

Regards,
Bengt Richter


Simon Brunning wrote:

On 9 Dec 2004 06:11:41 -0800, Egil M?ller <re****@takeit.se> wrote:

Is there any way to create transparent wrapper objects in Python?


This work - <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52295>?



Only for old-style classes, though. If you inherit from object or another
builtin, that recipe fails.

Cheers,
Nick.

--
Nick Coghlan | nc******@email.com | Brisbane, Australia
---------------------------------------------------------------
http://boredomandlaziness.skystorm.net


这篇关于包装对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆