[Tutor] Another Question
Michael P. Reilly
arcege@shore.net
Tue, 16 Jan 2001 11:10:54 -0500 (EST)
>
> --=====_97966014541=_
> Content-Type: text/plain; charset="WINDOWS-1250"
> Content-Transfer-Encoding: quoted-printable
>
> Sorry, I have so many question. Here is another one:
>
> class A:
> def fun(self, *options):
> ... # some codes here
>
> class B(A):
> def fun(self, *options):
> ...# some codes here
> ...# I need to call fun in class A here
>
> How can the method fun in class B use its option tuple to call the fun=
> method in the class A?
> The problem is caused because we can change the tuple (options).
Here is where the apply function comes in handy. A Python function's
arguments are broken into two parts: positional (tuple) and named
(dictionary). The apply function allows you to pass either or both
types to a function:
>>> def spam(*options, **keywords):
... print options, keywords
...
>>> spam(1, 2, 3, name='Arcege')
(1, 2, 3) {'name': 'Arcege'}
>>> spam(1, 2, 3)
(1, 2, 3) {}
>>> spam(name='Arcege')
() {'name': 'Arcege'}
>>> apply(spam, (1, 2, 3), {'name': 'Arcege'})
(1, 2, 3) {'name': 'Arcege'}
>>> apply(spam, (1, 2, 3))
(1, 2, 3) {}
Python 2.0 also has a new syntax to use instead of apply:
>>> spam(*(1,2,3), **{'name': 'Arcege'})
(1, 2, 3) {'name': 'Arcege'}
>>>
So in your example, the B.fun method could call:
class B(A):
def fun(self, *options):
if sys.version[:3] == '2.0':
A.fun( *( (self,) + options ) )
else:
apply( A.fun, (self,) + options )
Don't forget to include self as the first argument when calling unbound
methods.
-Arcege
--
------------------------------------------------------------------------
| Michael P. Reilly, Release Manager | Email: arcege@shore.net |
| Salem, Mass. USA 01970 | |
------------------------------------------------------------------------