473,324 Members | 2,531 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,324 software developers and data experts.

Adding method at runtime - problem with self

First of all, please don't flame me immediately. I did browse archives
and didn't see any solution to my problem.

Assume I want to add a method to an object at runtime. Yes, to an
object, not a class - because changing a class would have global
effects and I want to alter a particular object only. The following
approach fails:

class kla:
x = 1

def foo(self):
print self.x

k = kla()
k.foo = foo
k.foo()

I know where the problem is. The method shouldn't have 'self'
parameter. But how do I access object's attributes without it?

Best regards,

Marek

Mar 5 '06 #1
4 1775
ma*********@wp.pl wrote:
First of all, please don't flame me immediately. I did browse archives
and didn't see any solution to my problem.

Assume I want to add a method to an object at runtime. Yes, to an
object, not a class - because changing a class would have global
effects and I want to alter a particular object only. The following
approach fails:

class kla:
x = 1

def foo(self):
print self.x

k = kla()
k.foo = foo
k.foo()

I know where the problem is. The method shouldn't have 'self'
parameter. But how do I access object's attributes without it?

Best regards,

Marek


k.foo(k)
would work

Mar 5 '06 #2
ma*********@wp.pl a écrit :
First of all, please don't flame me immediately.
Granted - we'll do it later then !-)
I did browse archives
and didn't see any solution to my problem.

Assume I want to add a method to an object at runtime. Yes, to an
object, not a class - because changing a class would have global
effects and I want to alter a particular object only. The following
approach fails:

class kla:
x = 1

def foo(self):
print self.x

k = kla()
k.foo = foo
k.foo()

I know where the problem is. The method shouldn't have 'self'
parameter.
Yes it should - else :
But how do I access object's attributes without it?


Hey, how's Python itself doing ?-)

The problem with your code is that foo is a function object, not a
method object. So you need to turn it into a method object - which is
(overly simplification ahead) an object that bind a function object to
an instance and takes care of passing the instance as first param to
that function (hint: google for 'descriptor').

Hopefully, function objects provide a method that allow to bind them to
instances :
class Toto(object): .... def __init__(self, name): self.name = name
.... t1, t2 = Toto('t1'), Toto('t2')
def fun(self): .... print self.name t1.fun = fun.__get__(t1)
t1.fun()

t1

FWIW, you would have the same result (which much less pain) by simply
passing the instance to the function !-) (there's nothing special about
the word 'self')

If what you want to do is to provide a specific implementation for a
given method on a per-instance base, you can do it much more explicitely:

class MyObject(object):
def __init__(self, name, custom_do_this=None):
self.name = name
self._custom_do_this = custom_do_this

def _do_this_default(self):
return "default do_this implementation for %s" % self.name

def do_this(self):
if callable(self._custom_do_this):
return self._custom_do_this(self)
else:
return self._do_this_default()

def custom_do_this(obj):
return "custom do_this implementation for %s" % obj.name

myobj = MyObject('myobj')
print myobj.do_this()
myobj._custom_do_this = custom_do_this
print myobj.do_this()

Agreed, this is not exactly the same thing as *adding* a method, but
it's (IMHO) somewhat cleaner wrt/ encapsulation and LSP. (Note that you
can make the default implementation a no-op - the point here is that the
client code shouldn't have to worry about MyObject's instances having or
not having a custom implementation for do_this).

My 2 cents...
Mar 6 '06 #3
Thank you all for your responses. That's exactly what I needed to know
- how to bind a function to an object so that it would comply with
standard calling syntax.

This is largely a theoretical issue; I just wanted to improve my
understanding of Python's OOP model. Using such features in real life
code would probably be classified either as excessive magic or bad
design. Oh well, at least now I can be an informed participant of
language holy wars :-)

Marek

Mar 6 '06 #4
ma*********@wp.pl wrote:
Thank you all for your responses. That's exactly what I needed to know
- how to bind a function to an object so that it would comply with
standard calling syntax.

This is largely a theoretical issue; I just wanted to improve my
understanding of Python's OOP model. Using such features in real life
code would probably be classified either as excessive magic or bad
design.
or as a dirty-but-pragmatic workaround - just like accessing
implementation attributes. These are things that one should IMHO better
avoid if possible, but sometimes a simple hack is better than no
practical solution at all.
Oh well, at least now I can be an informed participant of
language holy wars :-)


Welcome on board !-)
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Mar 6 '06 #5

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

Similar topics

1
by: Holger Joukl | last post by:
Hi there, 2 questions regarding build/installation issues: 1. In the python 2.3.3 setup.py script, the detect_modules method of class PyBuildExt contains the following code: 253 if...
4
by: Max Derkachev | last post by:
Good day to all. Some time ago I'd been playing with a framework which uses dynamic class creation havily. Say, I could do: class A: pass # I method name is dynamic meth_name = 'foo'
0
by: Iker Arizmendi | last post by:
Hello all. Is there a convenient scheme within a C extension to add methods to a type in such a way as to allow me to transparently add a "proxy" around them? For example: typedef PyObject*...
8
by: Kevin Little | last post by:
#!/usr/bin/env python ''' I want to dynamically add or replace bound methods in a class. I want the modifications to be immediately effective across all instances, whether created before or...
3
by: Gabriele *darkbard* Farina | last post by:
Hi, there is a way to add methods to an object dynamically? I need to do something like this. I remember python allowed this ... class A(object): def do(s, m): print m @staticmethod def...
9
by: Mike | last post by:
I was messing around with adding methods to a class instance at runtime and saw the usual code one finds online for this. All the examples I saw say, of course, to make sure that for your method...
21
by: John Henry | last post by:
Hi list, I have a need to create class methods on the fly. For example, if I do: class Dummy: def __init__(self): exec '''def method_dynamic(self):\n\treturn self.method_static("it's...
3
by: zslevi | last post by:
Can I access the class attributes from a method added at runtime? (My experience says no.) I experimented with the following code: class myclass(object): myattr = "myattr" instance =...
1
by: Allen | last post by:
I need a way to add a method to an existing instance, but be as close as possible to normal instance methods. Using 'new' module or such code as 'def addfunc(...): def helper(...) .. setattr(...)'...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

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.