473,386 Members | 1,621 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,386 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 1673
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: 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: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
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: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

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.