Hi
I was recently thinking about the awkwardness I find in using the super
method to call a superclass's function.
The majority of the time I use super in the following way:
class Y(X):
def some_method(sel f, arg1, arg2):
do_something(ar g1)
arg2 += 1
super(Y, self).some_meth od(arg1, arg2)
The whole super(Y, self).some_meth od seems an awkward way to say "call
the superclass's version of this function".
So I defined a function that looks up the calling function name in the
stack frame and calls super on the self attribute, and returns the
function name:
import sys
def supermethod(cur rentclass):
callingframe = sys._getframe() .f_back
functionname = callingframe.f_ code.co_name
self = callingframe.f_ locals["self"]
superobject = super(currentcl ass, self)
return getattr(superob ject, functionname)
This then reduces the above to supermethod(Y)( arg1, arg2)
Of course explicit is better than implicit and so maybe not looking up
self is better:
import sys
def supermethod(cur rentclass, self):
callingframe = sys._getframe() .f_back
functionname = callingframe.f_ code.co_name
superobject = super(currentcl ass, self)
return getattr(superob ject, functionname)
This still means you call supermethod(Y, self)(arg1, arg2) instead of
super(Y, self).functionn ame(arg1, arg2)
Anyway I just wondered if others would find this interesting / useful /
material for a flame war :-)
David
I was recently thinking about the awkwardness I find in using the super
method to call a superclass's function.
The majority of the time I use super in the following way:
class Y(X):
def some_method(sel f, arg1, arg2):
do_something(ar g1)
arg2 += 1
super(Y, self).some_meth od(arg1, arg2)
The whole super(Y, self).some_meth od seems an awkward way to say "call
the superclass's version of this function".
So I defined a function that looks up the calling function name in the
stack frame and calls super on the self attribute, and returns the
function name:
import sys
def supermethod(cur rentclass):
callingframe = sys._getframe() .f_back
functionname = callingframe.f_ code.co_name
self = callingframe.f_ locals["self"]
superobject = super(currentcl ass, self)
return getattr(superob ject, functionname)
This then reduces the above to supermethod(Y)( arg1, arg2)
Of course explicit is better than implicit and so maybe not looking up
self is better:
import sys
def supermethod(cur rentclass, self):
callingframe = sys._getframe() .f_back
functionname = callingframe.f_ code.co_name
superobject = super(currentcl ass, self)
return getattr(superob ject, functionname)
This still means you call supermethod(Y, self)(arg1, arg2) instead of
super(Y, self).functionn ame(arg1, arg2)
Anyway I just wondered if others would find this interesting / useful /
material for a flame war :-)
David
Comment