通过对象方法替换整个对象 [英] Replace Whole Object Through Object Method

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

问题描述

对象如何使用自己的方法替换自身?请参阅

以下代码:


class Mixin:

def mixin(object,* classes):

NewClass = type(''Mixin'',(object .__ class __)+ classes,{})

newobj = NewClass()

newobj .__ dict__。 update(object .__ dict__)

return newobj


def isClass(object):

如果在str中''classobj'' (类型(对象)):

返回1

elif"''type''"在str(类型(对象)):

返回1

否则:

返回0

def listClasses( ):

classes = []

for eachals(globals()。keys():

if isClass(globals()[eachobj] ):

classes.append(globals()[eachobj])

打印eachobj

返回班级


def MixInto(Class,Mixin):

如果Mixin不在Class .__ bases__:

Class .__ bases__ + =(Mixin,)

------------------------------------------------ ------------------------


好​​的,所以mixin函数成为我选择的任何类的一部分

因此它的实例,但问题是我目前的方式

它设置mixin()返回一个新对象,而不是替换任何

类实例,将其调用到该新对象中。我希望我在这里制作

感觉。


基本上我需要的是能够找到名字的方法

的实例,然后我可以去全局字典做

的替换。


预感谢所有可以提供帮助的人。 ..

How can an object replace itself using its own method? See the
following code:

class Mixin:
def mixin(object, *classes):
NewClass = type(''Mixin'', (object.__class__,) + classes, {})
newobj = NewClass()
newobj.__dict__.update(object.__dict__)
return newobj

def isClass(object):
if ''classobj'' in str(type(object)):
return 1
elif "''type''" in str(type(object)):
return 1
else:
return 0
def listClasses():
classes = []
for eachobj in globals().keys():
if isClass(globals()[eachobj]):
classes.append(globals()[eachobj])
print eachobj
return classes

def MixInto(Class, Mixin):
if Mixin not in Class.__bases__:
Class.__bases__ += (Mixin,)
------------------------------------------------------------------------

Okay, so the mixin function becomes part of whatever class I choose and
hence its instances, but the problem is that the way I currently have
it setup mixin() returns a new object, instead of replacing whatever
class instance that calls it into that new object. I hope I''m making
sense here.

Basically what I need is for the method to be able to find out the name
of the instance, then I can just go to the globals dictionary to do the
replacement.

Advance thanks to all who can help...

推荐答案

Le lundi 26 juin 2006 17:57, di ************* @ gmail.com écrit*:
Le lundi 26 juin 2006 17:57, di*************@gmail.com a écrit*:
怎么能对象使用自己的方法替换自己?参见
以下代码:

类Mixin:
def mixin(对象,*类):
NewClass = type(''Mixin'',(对象。 __class __,)+ classes,{})
newobj = NewClass()
newobj .__ dict __。update(object .__ dict__)
返回newobj


python中的变量是名称,而不是对象,实例不应该知道

没有关于它们的引用方式。


我想你想要的是什么事实上,事情很简单,例如:


a = SomeClass()

a = a.some_method_wich_return_a_new_object()


或:


代表k,v代表globals()。iteritems():

if isinstance(v,SomeClass):

globlals()[k] = v.some_method_wich_return_a_new_object()

def isClass(object):
不要屏蔽内置名称。如果str中的'classobj'(类型(对象)):
为什么不直接测试类型?返回1
为清晰起见,Python有布尔值。

elif"''type''"在str(类型(对象)):
返回1
否则:
返回0
应该是:


导入类型


def isClass(object_):

if isinstance(object_,type):

return True#new style class

elif isinstance(object_,types.ClassType):

返回True#old-style class

else:return False


或者如果你不需要区分这些情况:


def isClass(object_):

返回isinstance(object_,type)或
isinstance(object_,types.ClassType)

def listClasses():
classes = []
用于globals()中的eachobj。 keys():
如果isClass(globals()[eachobj]):
classes.append(globals()[eachobj])
打印eachobj
返回类

def MixInto(Class,Mixin):
如果Mixin不在Class .__ bases__:
Class .__ bases__ + =(Mixin,)


这个母鹿在大多数情况下(使用新的样式类)不能工作,更好地重新接受从Class和Mixin继承的

类型,或者使用

Mixin .__ dict__继承Class .__ dict__ 。

----------------------------------------- -------------------------------

好的,所以mixin函数成为任何类的一部分我选择并且因此它的实例,但问题是我目前的方式
它设置mixin()返回一个新对象,而不是替换任何调用它的类实例新对象。我希望我在这里有意义。

基本上我需要的是方法能够找到实例的名称
然后我就可以了转到全球字典做
替换。

感谢所有可以提供帮助的人......
How can an object replace itself using its own method? See the
following code:

class Mixin:
def mixin(object, *classes):
NewClass = type(''Mixin'', (object.__class__,) + classes, {})
newobj = NewClass()
newobj.__dict__.update(object.__dict__)
return newobj

Variables in python are names, not the objects, and instances shouldn''t know
nothing about how they are referenced.

I guess what you want to do is, in fact, very simple somethig like :

a = SomeClass()
a = a.some_method_wich_return_a_new_object()

or :

for k, v in globals().iteritems() :
if isinstance(v, SomeClass) :
globlals()[k] = v.some_method_wich_return_a_new_object()

def isClass(object): Don''t mask builtin names. if ''classobj'' in str(type(object)): Why don''t you test the type directly ? return 1 Python has boolean for clarity.
elif "''type''" in str(type(object)):
return 1
else:
return 0 should be :

import types

def isClass(object_) :
if isinstance(object_, type) :
return True # new style class
elif isinstance(object_, types.ClassType) :
return True # old-style class
else : return False

or if you don''t need to diferentiate the cases :

def isClass(object_) :
return isinstance(object_, type) or \
isinstance(object_, types.ClassType)
def listClasses():
classes = []
for eachobj in globals().keys():
if isClass(globals()[eachobj]):
classes.append(globals()[eachobj])
print eachobj
return classes

def MixInto(Class, Mixin):
if Mixin not in Class.__bases__:
Class.__bases__ += (Mixin,)
This doesn''t work in most cases (with new style classes), better recreat a
type which inherit from Class and Mixin, or Class.__dict__ with
Mixin.__dict__.
------------------------------------------------------------------------

Okay, so the mixin function becomes part of whatever class I choose and
hence its instances, but the problem is that the way I currently have
it setup mixin() returns a new object, instead of replacing whatever
class instance that calls it into that new object. I hope I''m making
sense here.

Basically what I need is for the method to be able to find out the name
of the instance, then I can just go to the globals dictionary to do the
replacement.

Advance thanks to all who can help...




-

_____________


Maric Michaud

_____________


亚里士多德 - www.aristote.info

3 place des tapis

69004里昂

电话:+33 426 880 097



--
_____________

Maric Michaud
_____________

Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 426 880 097


di ************* @ gmail.com 写道:
一个对象如何使用它替换自己自己的方法?


AFAIK,它不可能(但我可能是错的 - 周围的一些大师?)。

请参阅
以下代码:< Mixin:
def mixin(object,* classes):
NewClass = type(''Mixin'',(object .__ class __)+ classes,{})
newobj = NewClass()
newobj .__ dict __。update(object .__ dict__)
返回newobj

def isClass(object):
if''classobj ''在str(类型(对象)):
返回1
elif"''type''"在str(类型(对象)):
返回1
否则:
返回0
def listClasses():
classes = []
for eachobj在globals()。keys():
如果isClass(globals()[eachobj]):
classes.append(globals()[eachobj])
打印eachobj
返回班级


FWIW:

Python 2.4.3(#1,2006年6月3日,17:26:11)

[ Linux2上的GCC 3.4.6(Gentoo 3.4.6-r1,ssp-3.4.5-1.0,pie-8.7.9)]
How can an object replace itself using its own method?
AFAIK, It can''t (but I can be wrong - some guru around ?).
See the
following code:

class Mixin:
def mixin(object, *classes):
NewClass = type(''Mixin'', (object.__class__,) + classes, {})
newobj = NewClass()
newobj.__dict__.update(object.__dict__)
return newobj

def isClass(object):
if ''classobj'' in str(type(object)):
return 1
elif "''type''" in str(type(object)):
return 1
else:
return 0
def listClasses():
classes = []
for eachobj in globals().keys():
if isClass(globals()[eachobj]):
classes.append(globals()[eachobj])
print eachobj
return classes
FWIW:
Python 2.4.3 (#1, Jun 3 2006, 17:26:11)
[GCC 3.4.6 (Gentoo 3.4.6-r1, ssp-3.4.5-1.0, pie-8.7.9)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
def dumbfactory():
.... class Dumb(object):pass

....类Dummy:传递

....返回Dumb,Dummy

.... globals()
{ ''__ builtin__'':< module''__ builtin__''(内置)>,''_ _ _ _ _ _'':

''__ main__'',''__ doc__'':无, ''dumbfactory'':< function dumbfactory at

0x2aaaaab66e60>} def fun():
.... dumb,dummy = dumbfactory()

....返回

.... fun()
globals()
{''__ builtin__'':< module''__ builtin__''(内置)>,''_ _ name__'':

''__ main__'',''fun'':<功能乐趣在0x2aaaaab66ed8>,''__ doc__'':无,

''dumbfactory'':<函数dumbfactory at 0x2aaaaab66e60>}


看起来像哑巴和虚拟赢了没有列出......还有:

级Mymeta(类型):
....传递

....类Foo(对象) :
.... __ metaclass__ = Mymeta

...."''type''" in str(type(globals()[''Mymeta'']))
def dumbfactory(): .... class Dumb(object): pass
.... class Dummy: pass
.... return Dumb, Dummy
.... globals() {''__builtins__'': <module ''__builtin__'' (built-in)>, ''__name__'':
''__main__'', ''__doc__'': None, ''dumbfactory'': <function dumbfactory at
0x2aaaaab66e60>} def fun(): .... dumb, dummy = dumbfactory()
.... return
.... fun()
globals() {''__builtins__'': <module ''__builtin__'' (built-in)>, ''__name__'':
''__main__'', ''fun'': <function fun at 0x2aaaaab66ed8>, ''__doc__'': None,
''dumbfactory'': <function dumbfactory at 0x2aaaaab66e60>}
Looks like dumb and dummy won''t get listed... And also:
class Mymeta(type): .... pass
.... class Foo(object): .... __metaclass__ = Mymeta
.... "''type''" in str(type(globals()[''Mymeta'']))



True


看起来这也会列出元类......可能也可能不是问题...

def MixInto(Class,Mixin):


你' '请注意,在这个函数的范围内,''Mixin''arg名称将

影子的Mixin类名? (抱歉问愚蠢的问题)。

如果Mixin不在Class .__ bases__:
Class .__ bases__ + =(Mixin,)
--------- -------------------------------------------------- -------------

好的,所以mixin函数成为我选择的任何类的一部分,因此它的实例,但问题是这样的方式我目前已经设置了mixin()返回一个新对象,而不是将调用它的任何类实例替换为该新对象。我希望我在这里有意义。

基本上我需要的是方法能够找到实例的名称
然后我就可以了转到全局字典做
替换。

感谢所有可以提供帮助的人...


True

Looks like this will list metaclasses too... May or may not be a problem...
def MixInto(Class, Mixin):
You''re aware that in this function''s scope, the ''Mixin'' arg name will
shadow the Mixin class name ? (sorry for asking dumb question).
if Mixin not in Class.__bases__:
Class.__bases__ += (Mixin,)
------------------------------------------------------------------------

Okay, so the mixin function becomes part of whatever class I choose and
hence its instances, but the problem is that the way I currently have
it setup mixin() returns a new object, instead of replacing whatever
class instance that calls it into that new object. I hope I''m making
sense here.

Basically what I need is for the method to be able to find out the name
of the instance, then I can just go to the globals dictionary to do the
replacement.

Advance thanks to all who can help...




而不是暴露您的解决方案的问题,您可能希望公开

真实用例?

-

bruno desthuilliers

python -c" print''@''。join([''。''。join([w [:: - 1] for w in p.split(''。'')])for ''o **** @ xiludom.gro''中的
p.split(''@'')])"



Instead of exposing problems with your solution, you may want to expose
the real use case ?
--
bruno desthuilliers
python -c "print ''@''.join([''.''.join([w[::-1] for w in p.split(''.'')]) for
p in ''o****@xiludom.gro''.split(''@'')])"




Maric Michaud写道:

Maric Michaud wrote:
Le lundi 26 juin 2006 17:57, di ************* @ gmail.com écrit:
Le lundi 26 juin 2006 17:57, di*************@gmail.com a écrit :
对象如何使用自己的方法替换自身?参见
以下代码:

类Mixin:
def mixin(对象,*类):
NewClass = type(''Mixin'',(对象。 __class __,)+ classes,{})
newobj = NewClass()
newobj .__ dict __。update(object .__ dict__)
返回newobj

python中的变量是名称,而不是对象,实例不应该知道它们是如何被引用的。

我想你想要做的事实上,非常简单,例如:< br => a = SomeClass()
a = a.some_method_wich_return_a_new_object()

或者:

对于k,v在globals()中。 iteritems():
if isinstance(v,SomeClass):
globlals()[k] = v.some_method_wich_return_a_new_object()

How can an object replace itself using its own method? See the
following code:

class Mixin:
def mixin(object, *classes):
NewClass = type(''Mixin'', (object.__class__,) + classes, {})
newobj = NewClass()
newobj.__dict__.update(object.__dict__)
return newobj

Variables in python are names, not the objects, and instances shouldn''t know
nothing about how they are referenced.

I guess what you want to do is, in fact, very simple somethig like :

a = SomeClass()
a = a.some_method_wich_return_a_new_object()

or :

for k, v in globals().iteritems() :
if isinstance(v, SomeClass) :
globlals()[k] = v.some_method_wich_return_a_new_object()

def isClass (对象):
def isClass(object):


不要屏蔽内置名称。


Don''t mask builtin names.




你的意思是对象?阴影/掩码仅存在于

函数的范围内。但无论如何,一点都很好。



You mean "object"? The shadow/mask only exists within the scope of the
function. But anyhow, point well taken.

如果str中的'classobj'(类型(对象)):
if ''classobj'' in str(type(object)):


你为什么不直接测试这个类型?


Why don''t you test the type directly ?




谢谢。



Thanks.

return 1


为了清晰起见,Python有布尔值。


Python has boolean for clarity.




谢谢。



Thanks.

elif"''类型 '' "在str(类型(对象)):
返回1
否则:
返回0应该是:

导入类型

def isClass (object_):
如果isinstance(object_,type):
返回True#新样式类
elif isinstance(object_,types.ClassType):
返回True#old-style上课
否则:返回False

或者如果你不需要区分案件:

def isClass(object_):
return isinstance (object_,type)或\
isinstance(object_,types.ClassType)
elif "''type''" in str(type(object)):
return 1
else:
return 0 should be :

import types

def isClass(object_) :
if isinstance(object_, type) :
return True # new style class
elif isinstance(object_, types.ClassType) :
return True # old-style class
else : return False

or if you don''t need to diferentiate the cases :

def isClass(object_) :
return isinstance(object_, type) or \
isinstance(object_, types.ClassType)




很干净!谢谢。




Very clean! Thank you.


def listClasses():
classes = []
for globals()。keys()中的eachobj :
如果isClass(globals()[eachobj]):
classes.append(globals()[eachobj])
打印eachobj
返回类
def MixInto(Class,Mixin):
如果Mixin不在Class .__ bases__:
Class .__ bases__ + =(Mixin,)
这在大多数情况下都不起作用(使用new样式类),更好地重新演绎继承自Class和Mixin的类型,或者使用
Mixin .__ dict __来继承Class .__ dict__。
def listClasses():
classes = []
for eachobj in globals().keys():
if isClass(globals()[eachobj]):
classes.append(globals()[eachobj])
print eachobj
return classes

def MixInto(Class, Mixin):
if Mixin not in Class.__bases__:
Class.__bases__ += (Mixin,)
This doesn''t work in most cases (with new style classes), better recreat a
type which inherit from Class and Mixin, or Class.__dict__ with
Mixin.__dict__.




什么不是什么工作? mixin的全部目的是为类添加

功能,因此在运行中添加它的所有实例。

创建新类型将无法实现此功能,除非那里是的东西

我很想念(非常可能!)。在大多数新时代案例中,你的意思是什么?
工作?似乎工作得很好......



What doesn''t work exactly? The whole purpose of the mixin is to add
functionality to the class and hence to all its instances on the fly.
Creating a new type would not achieve this, unless there''s something
I''m missing (a very real possibility!). And what do you mean doesn''t
work in most newstyleclass cases? Seems to be working just fine...

----------------------------- -------------------------------------------
好的,所以mixin函数成为我选择的任何类的一部分,因此它的实例,但问题是我目前的方式
它设置mixin()返回一个新对象,而不是替换无论是什么类实例都将它调用到那个新对象中。我希望我在这里有意义。

基本上我需要的是方法能够找到实例的名称
然后我就可以了转到全局字典做
替换。


任何回答我的主要问题吗?

感谢所有可以提供帮助的人...
------------------------------------------------------------------------

Okay, so the mixin function becomes part of whatever class I choose and
hence its instances, but the problem is that the way I currently have
it setup mixin() returns a new object, instead of replacing whatever
class instance that calls it into that new object. I hope I''m making
sense here.

Basically what I need is for the method to be able to find out the name
of the instance, then I can just go to the globals dictionary to do the
replacement.
Any answers my primary question though?

Advance thanks to all who can help...



- -
_____________

Maric Michaud
_____________

亚里士多德 - www.aristote.info
3 place des tapis
69004 Lyon
电话:+33 426 880 097



--
_____________

Maric Michaud
_____________

Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 426 880 097






这篇关于通过对象方法替换整个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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