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

Reusing object methods?


Can this be done: (this example doesn't work)

----
class A:

def a_lengthy_method(self, params):
# do some work depending only on data in self and params

class B:

def __init__(self):
self.a_lengthy_method = A.a_lengthy_method
# I know that data in "self" of class B object is compatible
# with that of class A object
----

I want to 'reuse' the same method from class A in class B, and without
introducing a common ancestor for both of them - is this possible in an
elegant, straightforward way?

Jul 19 '05 #1
6 1669
Ivan Voras wrote:
I want to 'reuse' the same method from class A in class B, and without
introducing a common ancestor for both of them - is this possible in an
elegant, straightforward way?

import new

class A: .... def foo(self):
.... print "Hello, %s!" % self.__class__.__name__
.... class B: .... def __init__(self):
.... self.foo = new.instancemethod(A.foo.im_func, self, B)
.... A().foo() Hello, A! B().foo()

Hello, B!
Jul 19 '05 #2
Ivan Voras wrote:
I want to 'reuse' the same method from class A in class B, and without
introducing a common ancestor for both of them - is this possible in an
elegant, straightforward way?


Straightforward, if not elegant:
def method(self, params): .... print self, params
.... class A: .... method = method
.... class B: .... method = method
.... A().method(42) <__main__.A instance at 0x402aadac> 42 B().method(42) <__main__.B instance at 0x402aadac> 42


Peter

Jul 19 '05 #3
On Fri, 29 Apr 2005 19:45:54 +0200, Ivan Voras <ivoras@_-_fer.hr> wrote:

Can this be done: (this example doesn't work)

----
class A:

def a_lengthy_method(self, params):
# do some work depending only on data in self and params

class B:

def __init__(self):
self.a_lengthy_method = A.a_lengthy_method
# I know that data in "self" of class B object is compatible
# with that of class A object
----

I want to 'reuse' the same method from class A in class B, and without
introducing a common ancestor for both of them - is this possible in an
elegant, straightforward way?


Your design intent is not quite clear to me, since you are trying to
capture the A method from B's instance initialization. If it is to be
a method of B, why not put the code in the class body of B instead
of in B.__init__, whose concern is B instances, not the B class (at least normally).
OTOH, if you really want an "instance-method" as an attribute of a B instance, see
class B below. Such a method is not shared by different instances, though the
example here doesn't demonstrate that, since they would all be clone instance-methods.
The C and D examples provide a shared method to their instances.

Here are some ways to do what you might be wanting to do ;-)
class A: ... def a_lengthy(self, params): return self, params
... class B: ... def __init__(self):
... self.a_lengthy = A.a_lengthy.im_func.__get__(self, type(self))
... class C: ... a_lengthy = A.a_lengthy.im_func
... class D: ... a_lengthy = A.__dict__['a_lengthy']
... a = A()
b = B()
c = C()
d = D()
a.a_lengthy('actual param') (<__main__.A instance at 0x02EF628C>, 'actual param') b.a_lengthy('actual param') (<__main__.B instance at 0x02EF618C>, 'actual param') c.a_lengthy('actual param') (<__main__.C instance at 0x02EF62EC>, 'actual param') d.a_lengthy('actual param') (<__main__.D instance at 0x02EF16CC>, 'actual param')
vars(a) {} vars(b) {'a_lengthy': <bound method instance.a_lengthy of <__main__.B instance at 0x02EF618C>>} vars(c) {} vars(d)

{}

Note that class B borrows the A method and makes an "instance-method" -- i.e.,
a bound method bound to the instance and set as an attribute of that instance
(which is why it shows up in vars(b)).

This mechanism could make customized instance-methods for different instances,
if you wanted to, since the class B is not modified by making variations.

A method is just a class variable whose value is a function, until it is
accessed as an attribute of either the class or an instance. What makes
it a method is the attribute-retrieval mechanism. So what you want to do
is possible, but A.a_lengthy_method is not the function, it is an unbound
method (because it was retrieved as an attribute of the class as opposed
to via an instance. For an ordinary method, you can get the function via
the im_func attribute, but if you want to borrow something trickier, you
may want to try the way class D does it.

For new-style classes, you will run across some differences.

Regards,
Bengt Richter
Jul 19 '05 #4
Hello!

Why not:
class A:
def a_lengthy_method(self, params):
# do some work depending only on data in self and params

class B(A): pass


?

Lg,
AXEL.
Jul 19 '05 #5
Axel Straschil wrote:
Hello!

Why not:

class A:
def a_lengthy_method(self, params):
# do some work depending only on data in self and params

class B(A): pass

?

Lg,
AXEL.


As a rough guess, I think the original poster was wondering how to
include *one* specific method from class A into B, without including all
the methods of A. Jp Calderone's suggestion of defining a special Mixin
class seems to be the cleanest implementation.

E.g.

class MyMixin:
""" Defines only a single method. It may be a debug call, or
a replacement for the classes' string representation. Etc. """
def a_lengthy_method(self,params):
# do some work

class A(MyMixin):
def other_lengthy_procedures(self, params):
pass

class B(MyMixin):
pass

The advantage of this is that you can define a normal inheritance tree
for a variety of classes, and then specifically override a single (or
group) of methods by placing the MyMixin class at the front of the
inheritance call. (The book "Programming Python" uses this a LOT in the
Tkinter section.)

E.g.

class C:
def well_now_what_do_we_do(self):
# stuff
def a_lengthy_method(self,params):
# This does the wrong stuff.

class D(MyMixin, C):
def __init__(self):
# blahblahblah

Now class D has the "correct" a_lengthy_method, inherited from MyMixin,
as well as all the other methods from class C, and the methods defined
in it's own class statement.

Joal

Jul 19 '05 #6
If you need just a single method once, don't use a mixin; just do
B.meth = A.meth.im_func. Do not underestimate the burden of
mixins on people reading your code (at least, for me it is burden,
since I have to draw the inheritance tree in my mind, look at which
methods are involved, wonder about the resolution order etc.)
Michele Simionato

Jul 19 '05 #7

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

Similar topics

2
by: Jo Voordeckers | last post by:
Hello all, I'm pretty new to the Java newsgroups so I apologize for dropping this into several maybe offtopic groups. I'm sorry! So on to my problem... I've come to a point in our RMI...
0
by: Oleg Paraschenko | last post by:
Hello, I'd like to introduce an article which might be of some interest: Reusing XML Processing Code in non-XML Applications HTML: http://uucode.com/texts/genxml/genxml.html PDF: ...
9
by: Alan | last post by:
Using VC++ (1998) compiler with PFE32 editor in Win2K Pro SP4. (DigitalMars CD on order. ) The program (below) instantiates a class and then deletes it. I would have thought that reusing the...
7
by: Klaus Johannes Rusch | last post by:
Is the following code valid and supported by current implementations? function somename() { this.show = function () { document.write("somename called") } } var somename = new somename();...
4
by: Old Wolf | last post by:
#include <stdio.h> #include <stdarg.h> Is this safe: void foo(const char *fmt, ...) { va_list ap; va_start(ap,fmt);
2
by: Bob | last post by:
How can I reuse an object that is already defined. I want to delete some files using the FileInfo class and the "name" is a read only property so I can't set the name as I want to. I don't want to...
4
by: Rob Meade | last post by:
Hi all, I'm in the middle of finishing a page and I've noticed that I have a chunk of code that is used in two places - its exactly the same - I guess I can rip this out - save it seperately and...
2
by: - Steve - | last post by:
I'm working on my asp.net site and I'm wondering what the best way to reuse little snippets of code is? Right now I have a Class in it's own cs file that I call Snippets. Then when I want to...
26
by: John Salerno | last post by:
I probably should find an RE group to post to, but my news server at work doesn't seem to have one, so I apologize. But this is in Python anyway :) So my question is, how can find all...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
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...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
by: marcoviolo | last post by:
Dear all, I would like to implement on my worksheet an vlookup dynamic , that consider a change of pivot excel via win32com, from an external excel (without open it) and save the new file into a...
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: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
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: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...

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.