Difference between 'function' and 'method'
castironpi at gmail.com
castironpi at gmail.com
Tue Mar 4 23:57:58 EST 2008
> > > >> >> Can you overload -type-'s decision of what to 'bind'?... whenever it
> > > >> >> is it makes it.
>
> > > >> >>>> from types import FunctionType, MethodType
> > > >> >>>> class A( FunctionType ): pass
> > > >> > ...
> > > >> > Traceback (most recent call last):
> > > >> > File "<stdin>", line 1, in <module>
> > > >> > TypeError: type 'function' is not an acceptable base type
>
> > > >> Use delegation instead of inheritance. This class is almost
> > > >> indistinguishable from a true function (when used as a method):
> > If P gets, p gotcha.
> > </joke>
>
> > gotcha= partial( get, you ). bor hor hor. Yes...
>
> Notwithstanding. Now bar has a name.
Now func has it.
from functools import wraps
class myfunction:
__slots__ = ('func','name')
#
def __init__(self, func):
@wraps( func )
def f( *ar, **kws ):
return func( self, *ar, **kws )
object.__setattr__(self, 'func', f)
object.__setattr__(self, 'name', None)
#
def __get__(self, instance, owner):
print( "__get__ called for",instance )
return self.func.__get__(instance, owner)
#
def __getattr__(self, name):
return getattr(self.func, name)
#
def __setattr__(self, name, value):
object.__setattr__(self.func, name, value)
class mymeta( type ):
def __init__( self, name, bases, namespace ):
for k,v in namespace.items():
if isinstance( v, myfunction ):
v.name= k
class P( metaclass= mymeta ):
def foo(self, x): print( 'foo',x )
#
@myfunction
def bar( fob,self, x): print( 'bar',fob,x )
p= P()
p.foo( 0 )
p.bar( 1 )
print( p.bar )
print( p.bar.name )
More information about the Python-list
mailing list