473,785 Members | 3,067 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

importing a method

hi,

I have an object defined with a number of hardcoded methods.

Class soandso:
def __init__(self):
self.this = 0
self.that = 1
def meth1(self):
...
def meth2(self):
...
def custom(self):
pass

I want to allow the user to write a python module that declares a
function so that myprogram can import it and attribute it to the custom
method of the soandso object. So far so good, that is an easy thing to
do in Python.

import usermodule
a=soandso()
a.custom = usermodule.func tion

But, what if the method had to access the self attributes (self.this
and self.that) of the soandso object?

Can it be done? and if so, what is the most Pythonic way of doing it?

thanks in advance,

Flávio

Nov 27 '05 #1
19 1864
Flavio <fc******@gmail .com> wrote:
Class soandso:
def __init__(self):
self.this = 0
self.that = 1
def meth1(self):
...
def meth2(self):
...
def custom(self):
pass

I want to allow the user to write a python module that declares a
function so that myprogram can import it and attribute it to the custom
method of the soandso object. So far so good, that is an easy thing to
do in Python.

import usermodule
a=soandso()
a.custom = usermodule.func tion
Apparently you haven't tested whether this works. It doesn't:
class Foo(object): ... pass
... def bar(*args): ... print "bar() got arguments:", args
... bar("spam", "eggs") bar() got arguments: ('spam', 'eggs') Foo.bar_method = bar
Foo.bar_method( "spam", "eggs") Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: unbound method bar() must be called with Foo instance as first argument (got str instance instead)
But, what if the method had to access the self attributes (self.this
and self.that) of the soandso object?


To become a method, the function must be bound to an instance, and the
method will then receive the instance as the first argument when
called as a method.

To do this on an already-defined function, use new.instancemet hod.
import new
help(new.instan cemethod)


--
\ "One time a cop pulled me over for running a stop sign. He |
`\ said, 'Didn't you see the stop sign?' I said, 'Yeah, but I |
_o__) don't believe everything I read.'" -- Steven Wright |
Ben Finney
Nov 28 '05 #2
why not just have your user subclass "soandso" and override the
definition of "custom"?

from soandso import soandso
class MyClass(soandso ):
def custom(self):
self.theother = 3

c = MyClass()

Nov 28 '05 #3
Because, by the time the user function is imported and attributed to
the custom method, soandso has already been instantiated and contains
the information tha needs to accessed by the user's function.

Nov 28 '05 #4
If you read my original post, I had no intention of atributing the
user's method to the class, but to the instance.

Anyway I figure it out myself, and its quite a Pythonic solution:
class Foo: name='John'
a=Foo() def p(parent): self=parent
print 'Hi, %s!'%self.name

a.met=p a.met(a)

Hi, John!

This works the same way an object's built-in method would work, since
all methods receive a reference to the parent object through the
required argument "self".

class Foo:
def met(self):
print self

Thanks for all the replies, they helped to catalize my own thoughts!

Flávio

Nov 28 '05 #5
There only one puzzle left to solve:

altough the solution I proposed works, this variant has problems:
class Foo: name='John'
a=Foo()
def p(): print 'Hi, %s!'%self.name a.met=p
a.met.self = a
a.met() NameError: global name 'self' is not defined

This error is paradoxical since:
a.met.self

<__main__.Foo instance at 0x405ed2ec>

Can anyone explain this?

Nov 28 '05 #6
Op 2005-11-27, Flavio schreef <fc******@gmail .com>:
hi,

I have an object defined with a number of hardcoded methods.

Class soandso:
def __init__(self):
self.this = 0
self.that = 1
def meth1(self):
...
def meth2(self):
...
def custom(self):
pass

I want to allow the user to write a python module that declares a
function so that myprogram can import it and attribute it to the custom
method of the soandso object. So far so good, that is an easy thing to
do in Python.

import usermodule
a=soandso()
a.custom = usermodule.func tion

But, what if the method had to access the self attributes (self.this
and self.that) of the soandso object?

Can it be done? and if so, what is the most Pythonic way of doing it?


You mean something like this:
class Foo: .... def __init__(self, v):
.... self.value = v
.... def show(self): .... print self.value
.... import new
f = Foo(17)
f.show = new.instancemet hod(show, f)
f.show()

17

--
Antoon Pardon
Nov 28 '05 #7
This "new" module sounds pretty cool, too bad its deprecated...

I would not want to add a dependancy to a deprecated module in my code.
But maybe I'll check the code for instancemethod within it and see what
it does.

Flávio

Nov 28 '05 #8
Addendum to my last reply:

although the New Method is deprecated,

new.instancemet hod (from Antoon's message) can be replaced by

from types import MethodType

f.show = MethodType(show ,f)

and every thing still works.

Nov 28 '05 #9
Flavio <fc******@gmail .com> wrote:
This "new" module sounds pretty cool, too bad its deprecated...

I would not want to add a dependancy to a deprecated module in my code.
But maybe I'll check the code for instancemethod within it and see what
it does.


If you have a function f and want to make an instancemethod out of it,
you can simply call f.__get__(thein stance, theclass) and that will build
and return the new instancemethod you require.
Alex
Nov 28 '05 #10

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

Similar topics

11
2235
by: Jeff Wagner | last post by:
I am importing a file which contains a persons name (firstName, middleName, etc). If I define a function to do this, how can I use the variables outside of that function? Here is the code: import string def getName(): data = open("enterName.txt")
2
2040
by: Awah Teh | last post by:
I am working on a project that involves importing IIS Log files into a SQL Server database (and these logfiles are big --> Some up to 2GB in size). Up until now I thought that DTS or the BULK INSERT command was the fastest method out there, but still proves to be long (taking an average of 45mns to an hour to process each log file). Because I have to import the log files from three web heads in my cluster (therefore 2GB log files per...
4
4704
by: Little PussyCat | last post by:
Hello, I nee to write something that will transfer excel data into an SQL Server table. I have for another database application I wrote have it importing Excel spreadsheet data using cell by cell, row by row method. This is fully automated so the user can choose whatever spreadsheet they want to import and press a button which sits on a VB6 frontend. This has been good for that situsation but it can be very slow when there
9
4035
by: Edward S | last post by:
I budget for a Project in an Excel sheet as illustrated below. The months below are usually a 2 year period i.e. 24 months, though it could be over 24 months depending upon a Project. I then need to input this in an Access database, where I do a comparison with the Actual cost. The table “TblBudget” in Access is made of 4 fields, namely: (1) CostElement (2) CostCenter (3) Month (4) Amount$. At the moment this method is very cumbersome....
14
1909
by: MLH | last post by:
GHudson has working procedures posted at http://www.access-programmers.co.uk/forums/showthread.php?t=66320 They work. Relationships, however, and some minor default settings are not preserved. Reestablishing some default settings and settings is a small price to pay for a set of text files that may save your database from total loss #AND# seem to remove the database bloat as well. I was wondering if someone knew how to preserve the...
7
3306
by: Timothy Shih | last post by:
Hi, I am trying to figure out how to use unmanaged code using P/Invoke. I wrote a simple function which takes in 2 buffers (one a byte buffer, one a char buffer) and copies the contents of the byte buffer into the character pointer. The code looks like the following: #include <stdio.h> #include <stdlib.h> #include "stdafx.h" BOOL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_call,
0
957
by: Ivan Lam | last post by:
Hi All, Thanks for reading my question. I am a newbie of VC .Net, and I am facing a problem about importing DLL. I have searched from the web and I download a simple sample. And the code is as follow:
3
1765
by: martin | last post by:
Hi, is there a dotnet function (other than the old isnumeric from VB) to check whether an object is numeric or not. also I notice that all the old vb functions such as split / isnumeric / ubound etc are still availible by default in any VB.net web application. is this because the vb library is being imported?? would it be best to totally remove this library (assuming that it is being imported - which I can't see in my references) so...
7
1965
by: hg | last post by:
Hi, I have the following problem. I find in a directory hierarchy some files following a certain sets of rules: ..../.../../plugin/name1/name1.py ..... ..../.../../plugin/namen/namen.py
2
1365
by: HMS Surprise | last post by:
Greetings, First I will admit I am new to Python but have experience with C++ and some Tcl/Tk. I am starting to use a tool called MaxQ that uses jython. I have been studying Rossum's tutorial but still am unclear on importing, the use of self, and calling functions with their own name in quotes. In the code below the lines between #Start and #End are generated by browsing web pages. In a large test this section can become quite large....
1
10091
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
9950
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8972
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7499
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6740
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4053
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
2
3646
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2879
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.