473,385 Members | 2,180 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,385 software developers and data experts.

extending methods ?

Hi,

the summary of my question is:
is there a way to append commands to a method inherited from
another class?

More verbose: Assume the following situation that I have
a class class_A with several methods.
In each of these methods quite a few computations take place
and several variables are defined.
Now I would like to extend this class to a class_B.
However, instead of overriding a method completely,
I would like to extend the method by basically adding
further commands at the end.

Eg., the code could look like:

class class_A:
def method1(self,x):
y=5*x+1 # create a variable
class class_B(class_A):
appendto method1(self,x):
print y # use variable defined in class_A
I.e. Effictively class_B should "look" like:

class class_B(class_A):
def method1(self,x):
y=5*x+1 # create a variable
print y # use the variable

Instead of this, one could in principle
store all variables defined in
method1 of class_A, eg. with self.y=y
and call in class_B the method1 of class_A.
However, with several variables and several methods
the code will not look nice.
(also efficiency is a bit of concern - presumably it shouldn't -
to me here as in my application the methods
are used to plot dots, circles, triangles etc.
so that speed is really important)

So is there a way to extend methods in the above sense
or is there a better (more pythonic ? ;-) approach to what I want?

Many thanks in advance.

Arnd

P.S.: Sorry if I messed up things on the OO side
(I am a real new-comer to this ...;-).
Jul 18 '05 #1
5 1830
Arnd Baecker wrote:
Hi,

the summary of my question is:
is there a way to append commands to a method inherited from
another class?
The canonical way to achieve that is to override the method,
and, within the override, call up to the superclass's
implementation.

More verbose: Assume the following situation that I have
a class class_A with several methods.
In each of these methods quite a few computations take place
and several variables are defined.
Ah, no way, then -- local variables of a method (just like
any other function) are totally internal to that method, and
there is absolutely no reasonable way to access them from
the outside.
However, with several variables and several methods
the code will not look nice.
A matter of opinion. I find it much nicer to know that a
local variable is local, and an instance variable is not.
(also efficiency is a bit of concern - presumably it shouldn't -
Right, it shouldn't. Local variables are fast BECAUSE they
are local. If they were non-local -- as you require, in order
to work with them from outside the defining method -- then
they wouldn't be fast.
to me here as in my application the methods
are used to plot dots, circles, triangles etc.
so that speed is really important)
I strongly doubt that the loss of speed due to making some
needed variable non-local is going to be measurable. Taking
your example...:

[alex@lancelot python2.3]$ python timeit.py \ -s 'class A:' \
-s ' def method1(self, x): y = 5 * x + 1' \
-s ' def method2(self, x): self.y = 5 * x + 1' \
-s 'a=A()' \
'a.method1(23)' 1000000 loops, best of 3: 1.47 usec per loop

and the same with method2 instead: 1.66 usec per loop.

What makes you think that a "slow-down" of 190 nanoseconds,
i.e. about 13% on this method call, is gonna be SO crucial?

And if you ARE working in an environment where every single
nanosecond matter, then what about...:

[alex@lancelot python2.3]$ python timeit.py \ -s 'class A:' \
-s ' def method1(self, x): y = 5 * x + 1' \
-s ' def method2(self, x): self.y = 5 * x + 1' \
-s 'a=A()' \ - -s 'meth=a.method2' \ 'meth(23)' 1000000 loops, best of 3: 1.25 usec per loop

See? Extracting the bound method once and for all saves
you a whopping *410* nanoseconds per call, compensating
the 190 "lost" by making instance variables where you need
them *and then some*. In other words, there are ways and
means to squeeze nanoseconds out of some Python bottleneck
that do not necessarily require using local variables where
you need instance or other non-local ones!

So is there a way to extend methods in the above sense
or is there a better (more pythonic ? ;-) approach to what I want?


There is no pythonic way to treat local variables as non-local.
(There MAY be horrible bytecode hacks exploiting hooks that are
meant for debugging only -- but THOSE *WILL* slow you down
SERIOUSLY...).
Alex

Jul 18 '05 #2
Arnd Baecker wrote:
Hi,

the summary of my question is:
is there a way to append commands to a method inherited from
another class?

More verbose: Assume the following situation that I have
a class class_A with several methods.
In each of these methods quite a few computations take place
and several variables are defined.
Now I would like to extend this class to a class_B.
However, instead of overriding a method completely,
I would like to extend the method by basically adding
further commands at the end.

Eg., the code could look like:

class class_A:
def method1(self,x):
y=5*x+1 # create a variable
class class_B(class_A):
appendto method1(self,x):
print y # use variable defined in class_A
I.e. Effictively class_B should "look" like:

class class_B(class_A):
def method1(self,x):
y=5*x+1 # create a variable
print y # use the variable

If you really want to do this, you are probably better off doing it
explicitly. For example
class A:
def store_locals(self, local_variables, keep_locals):
if keep_locals is None:
return
keep_locals.update(local_variables)

def m(self, x, keep_locals = None):
"""If you want to keep the local variables of this method,
specify a dictionary for keep_locals
"""
y = 5*x+1
self.store_locals(locals(), keep_locals)
class C(A):
def m(self, x, keep_locals = None):
if keep_locals is None:
keep_locals = {}
v = A.m(self, x, keep_locals = keep_locals)
print 'y was ', keep_locals['y']
return v

P.S.: Sorry if I messed up things on the OO side
(I am a real new-comer to this ...;-).


Perhaps if you tell us more about why you want to do this, we could come
up with a better OO solution.

David

Jul 18 '05 #3
In article <HyBeb.645796$YN5.495743@sccrnsc01>,
"David C. Fox" <da*******@post.harvard.edu> wrote:
Perhaps if you tell us more about why you want to do this, we could come
up with a better OO solution.


Actually this seems exactly the sort of thing for which aspect oriented
programming was developed.

http://www.google.com/search?q=aspect-oriented+python
seems to find a few relevant pages...

--
David Eppstein http://www.ics.uci.edu/~eppstein/
Univ. of California, Irvine, School of Information & Computer Science
Jul 18 '05 #4
On Wed, 1 Oct 2003 09:45:45 +0200 (CEST), Arnd Baecker
<ar**********@web.de> wrote:
the summary of my question is:
is there a way to append commands to a method inherited from
another class?


If you can call...

instance.method (arg1, ...)

then you can equivalently call...

classname.method (instance, arg1, ...)

You can use this in your subclasses method to call the method from a
specified base class (with multiple inheritance there may be more than
one base). For example...
class A (object) : .... def dostuff (self) :
.... print "running A.dostuff"
.... class B (A) : .... def dostuff (self) :
.... print "running B.dostuff"
.... A.dostuff (self)
.... b=B()
b.dostuff()

running B.dostuff
running A.dostuff
--
Steve Horne

steve at ninereeds dot fsnet dot co dot uk
Jul 18 '05 #5
David Eppstein <ep******@ics.uci.edu> wrote in
news:ep****************************@news.service.u ci.edu:
In article <HyBeb.645796$YN5.495743@sccrnsc01>,
"David C. Fox" <da*******@post.harvard.edu> wrote:
Perhaps if you tell us more about why you want to do this, we could
come up with a better OO solution.


Actually this seems exactly the sort of thing for which aspect
oriented programming was developed.


excuse me, but that is utterly and completely rubbish! :-) Specializing
methods is actually very useful, but I've only seen it in the language
Beta (well I'm certain it could be achieved in Simula 67 as well). In
simula classes and methods has been unified into the notion of a
"pattern". So since you can specialize classes, you now also can
specialize methods using this pattern construct.

AOP was designed to be able to define CROSS-CUTTING entities crosscutting
at least 2 inheritance hierachies.

You should all at least try to read up on the Beta language and grasp its
powerful idea of the pattern construct!

-carlo van dango
Jul 18 '05 #6

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

Similar topics

4
by: NadaHombre | last post by:
Hello, If I want to make a class which is a stack of objects of some specific type (not just "Objects"), what is the best way to do it? I wonder if there is some generally accepted "best" way to...
17
by: cwdjrxyz | last post by:
Javascript has a very small math function list. However there is no reason that this list can not be extended greatly. Speed is not an issue, unless you nest complicated calculations several levels...
1
by: Johannes Zellner | last post by:
Hello, when extending python there are type methods tp_iter and tp_iternext. Which python code calls the c iterator methods? -- Johannes
5
by: vbgunz | last post by:
Hello everyone. I own two books. Learning Python and Python in a nutshell. When cross referencing the two books to try and clarify the ideas behind extending methods and delegates, this is where...
1
by: rdaunoravicius | last post by:
Hi, Let's say you have a bunch of instatiated objects of the same class on your hands and you want to had some functionality to them. I'm facing this situation while working with PyGTK and...
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...
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: 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
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...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.