473,549 Members | 2,935 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Replace Whole Object Through Object Method

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...

Jun 26 '06 #1
23 1922
Le lundi 26 juin 2006 17:57, di************* @gmail.com a écrit*:
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_w ich_return_a_ne w_object()

or :

for k, v in globals().iteri tems() :
if isinstance(v, SomeClass) :
globlals()[k] = v.some_method_w ich_return_a_ne w_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(obje ct_, type) :
return True # new style class
elif isinstance(obje ct_, 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(obje ct_, type) or \
isinstance(obje ct_, 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
_____________

Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 426 880 097
Jun 26 '06 #2
di************* @gmail.com wrote:
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
.... 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(global s()['Mymeta']))

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...


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('@')])"
Jun 26 '06 #3

Maric Michaud wrote:
Le lundi 26 juin 2006 17:57, di************* @gmail.com a écrit :
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_w ich_return_a_ne w_object()

or :

for k, v in globals().iteri tems() :
if isinstance(v, SomeClass) :
globlals()[k] = v.some_method_w ich_return_a_ne w_object()

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.
if 'classobj' in str(type(object )):

Why don't you test the type directly ?


Thanks.
return 1

Python has boolean for clarity.


Thanks.
elif "'type'" in str(type(object )):
return 1
else:
return 0 should be :

import types

def isClass(object_ ) :
if isinstance(obje ct_, type) :
return True # new style class
elif isinstance(obje ct_, 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(obje ct_, type) or \
isinstance(obje ct_, types.ClassType )


Very clean! Thank you.


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__.


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...
------------------------------------------------------------------------

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
_____________

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


Jun 26 '06 #4

Bruno Desthuilliers wrote:
di************* @gmail.com wrote:
How can an object replace itself using its own method?
AFAIK, It can't (but I can be wrong - some guru around ?).
...


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
... 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(global s()['Mymeta'])) 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).


No sorry necessary, but yes, I am aware of it. Poor programming
practice I'm sure...
....
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...


Instead of exposing problems with your solution, you may want to expose
the real use case ?


***
I'm working with a team that's doing social modeling, and for example,
I need to model workers that at some point in the program may or may
not also become employers. Now, I want the workers to take on all
behaviors and attributes of an employer in addition to their
pre-existing "worker" behaviors and attributes. Also, as I'm sure you
guessed, the workers' attributes need to retain their values at that
point in the program, so a brand new worker-employer object wouldn't in
itself do the trick.
***


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


Jun 26 '06 #5

Maric Michaud wrote:
....
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__.


I think I've discovered precisely what you mean about problem with new
style classes. Do you know why it doesn't work for them? As I pointed
out, creating a new type doesn't achieve the same thing. Any
workarounds? Thanks.

Jun 26 '06 #6
di************* @gmail.com wrote:
Maric Michaud wrote:

(snip)
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_ _.

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.


very naïve solution:

def mixin(obj):

def someFunc(self, ...)
# code here
def someOtherFunc(s elf, ...)
# code here

cls = obj.__class__
cls.someFunc = someFunc
cls.someOtherFu nc = someOtherFunc

Just a bit less nïave solution:

def mixin(func):
func._mixin = True
return func

def mixable(func):
return getattr(attr, '_mixin', False):

class Mixin(object):
@mixin
def someFunc(self, ...):
# code here

@mixin
def someOtherFunc(s elf, ...)
# code here
def mix(cls, mixincls):
for name in dir(mixincls):
attr = getattr(mixincl s, name)
if callable(attr) and mixable(attr):
setattr(cls, name, attr)
Of course, one can do much better...
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
Jun 26 '06 #7
di************* @gmail.com a écrit :
Bruno Desthuilliers wrote: (snip)

Instead of exposing problems with your solution, you may want to expose
the real use case ?

I'm working with a team that's doing social modeling, and for example,
I need to model workers that at some point in the program may or may
not also become employers.


If I understand correctly, only some of the existing workers will become
employers ?
Now, I want the workers to take on all
behaviors and attributes of an employer in addition to their
pre-existing "worker" behaviors and attributes.
wrt/ behaviors, it's easy as pie. Attributes (I mean instance
attributes) are another problem, but I don't have enough informations to
deal with this problem here.
Also, as I'm sure you
guessed, the workers' attributes need to retain their values at that
point in the program, so a brand new worker-employer object wouldn't in
itself do the trick.


Here's a simple stupid possible solution:

class Worker(object):
def __init__(self, ...)
# init code here

# behaviours here

def becomeEmployer( self):
self.___class__ = Employer

class Employer(Worker ):
# behaviours here
w = Worker(...)
w.becomeEmploye r()

Note that there's no initializer in the Employer class - it wouldn't get
called anyway (not automatically at least).
Jun 26 '06 #8

Bruno Desthuilliers wrote:
di************* @gmail.com a écrit :
Bruno Desthuilliers wrote:

(snip)

Instead of exposing problems with your solution, you may want to expose
the real use case ?

I'm working with a team that's doing social modeling, and for example,
I need to model workers that at some point in the program may or may
not also become employers.


If I understand correctly, only some of the existing workers will become
employers ?
Now, I want the workers to take on all
behaviors and attributes of an employer in addition to their
pre-existing "worker" behaviors and attributes.


wrt/ behaviors, it's easy as pie. Attributes (I mean instance
attributes) are another problem, but I don't have enough informations to
deal with this problem here.
Also, as I'm sure you
guessed, the workers' attributes need to retain their values at that
point in the program, so a brand new worker-employer object wouldn't in
itself do the trick.


Here's a simple stupid possible solution:

class Worker(object):
def __init__(self, ...)
# init code here

# behaviours here

def becomeEmployer( self):
self.___class__ = Employer

class Employer(Worker ):
# behaviours here
w = Worker(...)
w.becomeEmploye r()

Note that there's no initializer in the Employer class - it wouldn't get
called anyway (not automatically at least).


Won't work because there will be employers that aren't workers.
And yes, only some workers will become employers, but also only some
employers will also be workers (at some point in program). Let me be
more clear:

workers
--> subset of workers --become--> employers
employers
--> subset of employers --become--> workers

It is very important that both should maintain attribute values,
regardless of whether they take on new "roles". Furthermore, this is a
very simple case and ultimately in my program an object should be able
to dynamically take on a multitude of roles (classes of behavior)
without mucking at all with their pre-existing states.

Jun 26 '06 #9
di************* @gmail.com a écrit :
Bruno Desthuilliers wrote:
di*********** **@gmail.com a écrit :
Bruno Desthuilliers wrote:
(snip)
Instead of exposing problems with your solution, you may want to expose
the real use case ?
I'm working with a team that's doing social modeling, and for example,
I need to model workers that at some point in the program may or may
not also become employers.


If I understand correctly, only some of the existing workers will become
employers ?

Now, I want the workers to take on all
behaviors and attributes of an employer in addition to their
pre-existing "worker" behaviors and attributes.


wrt/ behaviors, it's easy as pie. Attributes (I mean instance
attributes) are another problem, but I don't have enough informations to
deal with this problem here.

Also, as I'm sure you
guessed, the workers' attributes need to retain their values at that
point in the program, so a brand new worker-employer object wouldn't in
itself do the trick.


Here's a simple stupid possible solution:

(snip)
Won't work because there will be employers that aren't workers.
Then don't subclass Employer from Worker !-)

(don't mind, just kidding)
And yes, only some workers will become employers,

but also only some
employers will also be workers (at some point in program). Let me be
more clear:

workers
--> subset of workers --become--> employers
employers
--> subset of employers --become--> workers

It is very important that both should maintain attribute values,
regardless of whether they take on new "roles".
Seems obvious. But just a question, BTW: do workers and employers share
the same attributes ? And if not, how do you intend to initialize the
employers attributes on workers (and the other way round) ?
Furthermore, this is a
very simple case and ultimately in my program an object
*Any* object ?-)
should be able
to dynamically take on a multitude of roles (classes of behavior)
without mucking at all with their pre-existing states.


Multiple roles at the same time, or sequentially ? And in the first case
(which I assume), do you have the case of overriding behaviors ? And if
yes, how should the resolution order be defined ? And what about
attributes ? (I mean, do your 'roles' have specific attributes ?)
FWIW, just another simple (and very Q&D) snippet:

class ObjectWithRoles (object):
def _change(self, *bases):
self.__class__ = type(self.__cla ss__.__name__, bases, {})

def has_role(self, role):
return role in self.__class__. __bases__

def add_role(self, role):
if not self.has_role(r ole):
self._change(se lf.__class__, role)

def remove_role(sel f, role):
if self.has_role(r ole):
self._change(*( cls for cls in self.__class__. __bases__ \
if cls is not role))
NB : Not tested (and not sure what it'll do) with roles subclassing
other roles, or ObjectWithRoles as roles...

wrt/ per-role attributes, you'd of course need to pass them to
add_role(). A convenient way of maintaining some sanity here would be to
use descriptors for all of these attributes, and store their values in a
per-role dict, with the role name as attribute name.
Jun 27 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
2508
by: Roose | last post by:
How can I do a "".replace operation which tells me if anything was actually replaced? Right now I am doing something like: if searchTerm in text: text = text.replace( searchTerm, 'other' ) But to me this seems inefficient since the 'in' operation will search through the whole string, and then the 'replace' will as well.
12
8140
by: Barnes | last post by:
Does anyone know of a good way to use the JavaScript string.replace() method in an ASP form? Here is the scenario: I have a form that cannot accept apostrophes. I want to use the replace() so that the apostrophe is automatically replace with two '' . Reason being--SQL Server does not like apostrophes being sent to database. I've tried to...
1
16330
by: Thomas | last post by:
It looks like the String.replace doesn't work in IE6.1. Anyone else has the same problem. I am using newest service package of IE and Win2K. Thanks
12
4020
by: Brian | last post by:
I want to use regxp to check that a form input contains at least 1 non-space charcter. I'd like to only run this if the browser supports it. For DOM stuff, I'd use if (documentGetElementById) {} Is there an object/feature detection I can use to check for regxp string manipulation support? --
2
11501
by: Mike | last post by:
My page populates a table with a list of names and other information from a JavaScript object. I receive changes (adds, change & delete) to that list, convert it into a JavaScript object. I do understand how to add the new names to the list. I have 3 questions: 1) How can I search through the table rows to find the rows to be changed...
7
1583
by: Jeff Grippe | last post by:
Hello and thanks in advance for the help. I have been looking for a way to easily eliminate or disable the "Back" button on some of my web pages. I was reading my Javascript for Dummies Quick Reference and came upon the replace method. The book says: "The replace() method of the location object replaces the current history entry with the...
1
1990
by: JAG | last post by:
I am getting an error using the replace method in one of my functions. I am using the replace method in the mail document function in my frameset .hta to change forward slashes to back slashes in the myVar string. The myVar string is obtained in my show document function: myVar = filename; In my mail document function:
1
2101
by: shapper | last post by:
Hello, I have a XLST file where I have the phrase "HERE". Something like: <xsl:text>HERE</xsl:text> I want to replace "HERE" by "UPDATED" and save the file.
1
3383
by: NvrBst | last post by:
I want to use the .replace() method with the regular expression /^ %VAR % =,($|&)/. The following DOESN'T replace the "^default.aspx=,($|&)" regular expression with "": --------------------------------- myStringVar = myStringVar.replace("^" + iName + "=,($|&)", ""); --------------------------------- The following DOES replace it though:...
0
7446
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7715
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7469
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7808
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6040
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5087
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
1
1935
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1057
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
757
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.