473,382 Members | 1,357 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,382 software developers and data experts.

Adding methods to instances

Here's what I'm trying to do; please let me know if I'm nuts or
not.

Given a string consisting of the code you would normally define
in a class's method, add that compiled code to an instance of that
class so that it can be called just like any other bound method.
Here's an example:

xx = """def dynamic(self):
print "dynamic", self.testAtt
"""

class Test(object):
testAtt = "sample"
def normalMethod(self):
print "normal", self.testAtt

testInstance = Test()
# Here's where the magic is needed
# so that the rest of this example works.
testInstance.normal()
-> 'normal', 'sample'
testInstance.dynamic()
-> 'dynamic', 'sample'

So? Am I nuts? Or is this possible?

-- Ed Leafe
-- http://leafe.com
-- http://dabodev.com


Dec 15 '05 #1
8 1134
Il 2005-12-15, Ed Leafe <ed@leafe.com> ha scritto:
Here's what I'm trying to do; please let me know if I'm nuts or
not.

Given a string consisting of the code you would normally define
in a class's method, add that compiled code to an instance of that
class so that it can be called just like any other bound method.
Here's an example:

xx = """def dynamic(self):
print "dynamic", self.testAtt
"""

class Test(object):
testAtt = "sample"
def normalMethod(self):
print "normal", self.testAtt

testInstance = Test()
# Here's where the magic is needed
# so that the rest of this example works.
testInstance.normal()
-> 'normal', 'sample'
testInstance.dynamic()
-> 'dynamic', 'sample'

So? Am I nuts? Or is this possible?


Yes it is, use exec() to turn your string in valid Python code
and bind the dynamic function as a method of class Test

xx = """def dynamic(self):
print "dynamic", self.testAtt
"""

exec xx

class Test(object):
testAtt = "sample"
def normalMethod(self):
print "normal", self.testAtt

t = Test()
Test.dynamic = dynamic
t.dynamic()

--
Lawrence - http://www.oluyede.org/blog
"Anyone can freely use whatever he wants but the light at the end
of the tunnel for most of his problems is Python"
Dec 15 '05 #2
On Dec 15, 2005, at 11:51 AM, Lawrence Oluyede wrote:
So? Am I nuts? Or is this possible?


Yes it is, use exec() to turn your string in valid Python code
and bind the dynamic function as a method of class Test

xx = """def dynamic(self):
print "dynamic", self.testAtt
"""

exec xx

class Test(object):
testAtt = "sample"
def normalMethod(self):
print "normal", self.testAtt

t = Test()
Test.dynamic = dynamic
t.dynamic()


Thanks! I knew I had done this before. My mistake was that I was
setting the exec'd code to the instance, and not to the class. That
works, but makes it a function, which doesn't automatically get sent
the 'self' reference.

-- Ed Leafe
-- http://leafe.com
-- http://dabodev.com

Dec 15 '05 #3
Op 2005-12-15, Ed Leafe schreef <ed@leafe.com>:
On Dec 15, 2005, at 11:51 AM, Lawrence Oluyede wrote:
So? Am I nuts? Or is this possible?


Yes it is, use exec() to turn your string in valid Python code
and bind the dynamic function as a method of class Test

xx = """def dynamic(self):
print "dynamic", self.testAtt
"""

exec xx

class Test(object):
testAtt = "sample"
def normalMethod(self):
print "normal", self.testAtt

t = Test()
Test.dynamic = dynamic
t.dynamic()


Thanks! I knew I had done this before. My mistake was that I was
setting the exec'd code to the instance, and not to the class. That
works, but makes it a function, which doesn't automatically get sent
the 'self' reference.


But this will make the function a method to all instances of the class.
Is that what you want? From your first post I had the impression you
only wanted the function to be the method of one particular instance.

--
Antoon Pardon
Dec 16 '05 #4
To avoid that:
- subclass Test first

class SubclassTest(T):
pass

- assign the method to SubclassTest's attribute,

SubclassTest.dynamic = dynamic

- then assign the new class to magic variable __class__ :

t.__class__ = SubclassTest

t.dynamic()

Antoon Pardon wrote:
But this will make the function a method to all instances of the class.
Is that what you want? From your first post I had the impression you
only wanted the function to be the method of one particular instance.

Dec 16 '05 #5
Antoon Pardon <ap*****@forel.vub.ac.be> wrote:
Op 2005-12-15, Ed Leafe schreef <ed@leafe.com>:
On Dec 15, 2005, at 11:51 AM, Lawrence Oluyede wrote:
So? Am I nuts? Or is this possible?

Yes it is, use exec() to turn your string in valid Python code
and bind the dynamic function as a method of class Test

xx = """def dynamic(self):
print "dynamic", self.testAtt
"""

exec xx

class Test(object):
testAtt = "sample"
def normalMethod(self):
print "normal", self.testAtt

t = Test()
Test.dynamic = dynamic
t.dynamic()


Thanks! I knew I had done this before. My mistake was that I was
setting the exec'd code to the instance, and not to the class. That
works, but makes it a function, which doesn't automatically get sent
the 'self' reference.


But this will make the function a method to all instances of the class.
Is that what you want? From your first post I had the impression you
only wanted the function to be the method of one particular instance.


How about:

def bind(fun, arg):
return lambda *a, **k: fun(arg, *a, **k)

t.dynamic = bind(dynamic, t)

--
Ben Hutchings
The world is coming to an end. Please log off.
Dec 16 '05 #6
You can also just use:

t.dynamic = dynamic.__get__(t)

Dec 16 '05 #7
On Dec 16, 2005, at 7:55 AM, Antoon Pardon wrote:
But this will make the function a method to all instances of the
class.
Is that what you want? From your first post I had the impression you
only wanted the function to be the method of one particular instance.


Yes, you're correct - I hadn't noticed that, since all my tests
had single instances.

-- Ed Leafe
-- http://leafe.com
-- http://dabodev.com


Dec 17 '05 #8
On Dec 16, 2005, at 6:26 PM, zi************@gmail.com wrote:
You can also just use:

t.dynamic = dynamic.__get__(t)


OK, I've tried that, and it does indeed work well. I've never
had occasion to use descriptors before, and while it's clear what's
going on, it still has a 'magical' feel to it!

-- Ed Leafe
-- http://leafe.com
-- http://dabodev.com


Dec 17 '05 #9

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

Similar topics

14
by: pablo | last post by:
Dear NewsGroupers, I am relatively new to OOP and cannet get my head around this problem. I have two classes. Class Child extends Parent. There is no constructor for the Child class. So when I...
99
by: David MacQuigg | last post by:
I'm not getting any feedback on the most important benefit in my proposed "Ideas for Python 3" thread - the unification of methods and functions. Perhaps it was buried among too many other less...
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...
11
by: Steven D'Aprano | last post by:
Suppose I create a class with some methods: py> class C: .... def spam(self, x): .... print "spam " * x .... def ham(self, x): .... print "ham * %s" % x .......
3
by: MIGUEL | last post by:
Hi all, I'm quite lost with how adding web references to a project creates proxy classes. I've developed a web service with two classes inside and that contains three references to three...
47
by: Albert | last post by:
So structures are useful to group variables, so you can to refer to a collection as a single entity. Wouldn't it be useful to also have the ability to collect variable and functions? Ask K&R...
3
by: rickeringill | last post by:
Hi comp.lang.javascript, I'm throwing this in for discussion. First up I don't claim to be any sort of authority on the ecmascript language spec - in fact I'm a relative newb to these more...
26
by: Cliff Williams | last post by:
Can someone explain the pros/cons of these different ways of creating a class? // 1 function myclass() { this.foo1 = function() {...} } // 2a
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: 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...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?

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.