只替换一个对象的mothod,而不是类 [英] replace mothod for only one object but not for a class

查看:66
本文介绍了只替换一个对象的mothod,而不是类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述




我有多个对象都属于同一个类

(我没有实现,我的代码我不是''我想要修改)


现在我想只为一个对象更改一个方法(在创建了
之后),而不添加任何开销

来调用其他对象的方法。

这可能吗?


例子

#####这不是我想要做的事情

#####因为它覆盖了这个类的所有对象的方法

o1 = aclass()

o2 = aclass()

#调用原始方法

o1.method()

o2.method()

#覆盖整个班级的方法

aclass.method = mymethod

o1.method()#现在新方法

o2.method()#now new method

#######什么不起作用,但我想要的是什么做

o1 = aclass()

o2 = aclass()

#call origi nal方法

o1.method()

o2.method()

#覆盖整个班级的方法

o1.method = mymethod

o1.method()#now new method

o2.method()#still old method

thanks任何指针。

PS我想,有一个计算机科学术语,我试图实现


如果有人知道,我也有兴趣学习它。

解决方案

来自functools import partial


class点数:

def __init __(self,x,y):

self.x,self.y = x,y


def show(self,n):

for i in range(n):

print" Point:(%s,%s)" %(self.x,self.y)


def new_method(obj,func):

def方法(* args,** kw):

返回func(obj,* args,** kw)


返回方法

p1 = Point(1,2)< br $>
p2 = Point(3,4)


def show(self,n):

print" not a Point: %S-%S" %(self.x,self.y)

p2.show = partial(show,p2)


p1.show(3)

p2.show(3)


HTH,

-

Miki< mi **** *****@gmail.com>
http://pythonwise.blogspot.com


10月14日下午1:50,hofer< bla ... @ dungeon.dewrote:





我有多个对象都属于同一个类

(我没有实现,我的代码也没有我想修改


现在我想只为一个对象更改一个方法(在创建了
之后)而不添加任何开销

来调用其他对象的方法。


这可能吗?


示例

#####这不是我想要做的事情

#####因为它覆盖了这个类的所有对象的方法

o1 = aclass()

o2 = aclass()

#调用原始方法

o1.method()

o2.method()

#覆盖整个班级的方法

aclass.method = mymethod

o1 .method()#now new method

o2.method()#now new method


#######什么行不通,但是我想做什么

o1 = aclass()

o2 = aclass()

#调用原始方法

o1.method()

o2.method()

#覆盖整个班级的方法

o1。 method = mymethod

o1.method()#now new method

o2.method()#still old method


谢谢对于任何指针。



请发布不起作用的实际代码。以下作为

预期:


>> A类(对象):



... def foo(self):return''Original''

...


>> a = A()
b = A()
a.foo()



''Original''


>> b.foo()



''原始''


>> b.foo = lambda:''修改''
a.foo()



''原创'


>> b.foo()



''已修改''

HTH,

George


10月14日,11:20 * am,George Sakkis< george.sak ... @ gmail.comwrote:


10月14日,下午1点50分,hofer< bla ... @ dungeon.dewrote:




我有多个对象都属于同一个类

*(我没有实现,我的代码我不想修改)


现在我想仅为一个对象更改一个方法(在创建了
之后),而不添加任何开销

来调用其他对象的方法。


这可能吗?


例子

#####这不是我想做的事情

#####因为它覆盖了这个类的所有对象的方法

o1 = aclass()

o2 = aclass()

#调用原始方法

o1.method()

o2.method()

#覆盖整个类的方法

aclass.method = mymethod

o1.method()#now new method

o2.method()#now new method


#######什么行不通,但我想做什么

o1 = aclass ()

o2 = aclass()

#调用原始方法

o1.method()

o2。方法()

#覆盖整个班级的方法

o1.method = mymethod

o1.method()#now new method

o2.method()#still old method


感谢任何指针。



请发布不起作用的实际代码。以下作品预期为




* *>> A类(对象):

* * .. 。* * def foo(self):return''Original''

* * ...

* *>> a = A()

* *>> b = A()

* *>> a.foo()

* *''原创''

* *>> b.foo()

* *''原创''

* *>> b。 foo = lambda:''已修改''

* *>> a.foo()

* *''原创''

* *>> b.foo()

* *'''已修改''


HTH,

George



你在做什么叫做monkeypatching。我认为这很危险,但是对于他自己的每个人来说都是b $ b。 Python的元编程设施可以处理它.B



lambda方法可能会泄漏,我有什么垃圾收集问题

在绑定方法周围移动(我的对象没有被收集

预期,基本上)。部分方法也很酷,但它不会可靠地处理像__getattr__和__setattr __,

这样的东西,我也学到了很多东西。关于它的可能最好的方法是定义一个实现你的方法的新类,并且

使用一些动态魔法来创建一个新类继承自

你的monkeypatch类和当前实例的类:


在[2]中:class main_implementation(object):

...:def a(self):

...:打印''a''

...:def b(self, argb =''b''):

...:打印''B说%r''%argb

......:

...:


在[6]中:class new_implementation_of_a(object):

...:def a(self):

...:print这是A的新实现

......:

......:


在[7]中:mymain = main_implementation()


在[8]中:mymain.a()

a


在[9]中:mymain .__ class__ = type(mymain .__ class __.__ name __ +''MODIFIED'',

(new_implementation_of_a, mymain .__ class__),{})


在[10]中:mymain

Out [10]:< __ main __。main_implementationMODIFIED对象位于0x0137EA50>


在[11]中:mymain.a()

这是A的新实现

In [12] ]:mymain.b()

B说''b''


当您使用动态创建新类时,会出现这种魔力

type()内置函数并将其分配给实例的__class__

属性。


祝你好运。


Hi,

I have multiple objects all belonging to the same class
(which I didn''t implement and whose code I don''t want to modify)

Now I''d like to change one method for one object only (after it has
been created) without adding any overhead
to the call of the other object''s methods.
Is this possible?

Example
##### This is NOT what I''d like to do
##### as it overwrites the method for all objects of this class
o1 = aclass()
o2 = aclass()
# call original method
o1.method()
o2.method()
# overwrite the method for the entire class
aclass.method = mymethod
o1.method() # now new method
o2.method() # now new method
####### What doesn''t work, but what I''d like to do
o1 = aclass()
o2 = aclass()
# call original method
o1.method()
o2.method()
# overwrite the method for the entire class
o1.method = mymethod
o1.method() # now new method
o2.method() # still old method
thanks for any pointers.
P.S. I guess, that there is a computer science term for what I try to
achieve.
If anybody knew it I would be interested to learn it as well.

解决方案

from functools import partial

class Point:
def __init__(self, x, y):
self.x, self.y = x, y

def show(self, n):
for i in range(n):
print "Point: (%s, %s)" % (self.x, self.y)

def new_method(obj, func):
def method(*args, **kw):
return func(obj, *args, **kw)

return method
p1 = Point(1, 2)
p2 = Point(3, 4)

def show(self, n):
print "Not a Point: %s-%s" % (self.x, self.y)
p2.show = partial(show, p2)

p1.show(3)
p2.show(3)

HTH,
--
Miki <mi*********@gmail.com>
http://pythonwise.blogspot.com


On Oct 14, 1:50 pm, hofer <bla...@dungeon.dewrote:

Hi,

I have multiple objects all belonging to the same class
(which I didn''t implement and whose code I don''t want to modify)

Now I''d like to change one method for one object only (after it has
been created) without adding any overhead
to the call of the other object''s methods.

Is this possible?

Example
##### This is NOT what I''d like to do
##### as it overwrites the method for all objects of this class
o1 = aclass()
o2 = aclass()
# call original method
o1.method()
o2.method()
# overwrite the method for the entire class
aclass.method = mymethod
o1.method() # now new method
o2.method() # now new method

####### What doesn''t work, but what I''d like to do
o1 = aclass()
o2 = aclass()
# call original method
o1.method()
o2.method()
# overwrite the method for the entire class
o1.method = mymethod
o1.method() # now new method
o2.method() # still old method

thanks for any pointers.

Please post the actual code that doesn''t work. The following works as
expected:

>>class A(object):

... def foo(self): return ''Original''
...

>>a = A()
b = A()
a.foo()

''Original''

>>b.foo()

''Original''

>>b.foo = lambda: ''Modified''
a.foo()

''Original''

>>b.foo()

''Modified''
HTH,
George


On Oct 14, 11:20*am, George Sakkis <george.sak...@gmail.comwrote:

On Oct 14, 1:50 pm, hofer <bla...@dungeon.dewrote:

Hi,

I have multiple objects all belonging to the same class
*(which I didn''t implement and whose code I don''t want to modify)

Now I''d like to change one method for one object only (after it has
been created) without adding any overhead
to the call of the other object''s methods.

Is this possible?

Example
##### This is NOT what I''d like to do
##### as it overwrites the method for all objects of this class
o1 = aclass()
o2 = aclass()
# call original method
o1.method()
o2.method()
# overwrite the method for the entire class
aclass.method = mymethod
o1.method() # now new method
o2.method() # now new method

####### What doesn''t work, but what I''d like to do
o1 = aclass()
o2 = aclass()
# call original method
o1.method()
o2.method()
# overwrite the method for the entire class
o1.method = mymethod
o1.method() # now new method
o2.method() # still old method

thanks for any pointers.


Please post the actual code that doesn''t work. The following works as
expected:

* * >>class A(object):
* * ... * * def foo(self): return ''Original''
* * ...
* * >>a = A()
* * >>b = A()
* * >>a.foo()
* * ''Original''
* * >>b.foo()
* * ''Original''
* * >>b.foo = lambda: ''Modified''
* * >>a.foo()
* * ''Original''
* * >>b.foo()
* * ''Modified''

HTH,
George

What you''re doing is called monkeypatching. I consider it dangerous,
but to each his own. Python''s metaprogramming facilities can handle
it.

The lambda approach can leak, I''ve had garbage collection issues when
shuffling around bound methods (my objects weren''t being collected
when expected, basically). The partial approach is cool, too, but it
won''t reliably work with things like __getattr__ and __setattr__,
which I also learned the hard way. The probable best way of going
about it is to define a new class that implements your one method, and
use some on-the-fly magic to create a NEW class that inherits from
both your monkeypatch class and your current instance''s class:

In [2]: class main_implementation(object):
...: def a(self):
...: print ''a''
...: def b(self, argb=''b''):
...: print ''B says %r'' % argb
...:
...:

In [6]: class new_implementation_of_a(object):
...: def a(self):
...: print "This is a new implementation of A"
...:
...:

In [7]: mymain = main_implementation()

In [8]: mymain.a()
a

In [9]: mymain.__class__ = type(mymain.__class__.__name__+''MODIFIED'',
(new_implementation_of_a, mymain.__class__), {})

In [10]: mymain
Out[10]: <__main__.main_implementationMODIFIED object at 0x0137EA50>

In [11]: mymain.a()
This is a new implementation of A

In [12]: mymain.b()
B says ''b''

The magic here occurs when you create a new class on-the-fly using the
type() built-in function and assign it to the instance''s __class__
attribute.

Good luck.


这篇关于只替换一个对象的mothod,而不是类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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