Difference between 'function' and 'method'
castironpi at gmail.com
castironpi at gmail.com
Thu Mar 6 19:56:33 EST 2008
On Mar 6, 5:35 am, "Gabriel Genellina" <gagsl-... at yahoo.com.ar> wrote:
> En Wed, 05 Mar 2008 02:57:58 -0200, <castiro... at gmail.com> escribi�:
>
>
>
>
>
> >> > > >> >> Can you overload -type-'s decision of what to 'bind'?...
> >> whenever it
> >> > > >> >> is it makes it.
>
> >> > > >> Use delegation instead of inheritance. This class is almost
> >> > > >> indistinguishable from a true function (when used as a method):
>
> >> 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 )
>
> Mmm, looks too complicated and I don't see any advantage over the original
> code. Functions already know their (original) name: func_name. If `name`
> was just an example, note that functions already have writeable attributes
> too, and my code exposes them as well. This should work with that version
> (untested):
>
> p = P()
> print p.bar.func_name # -> bar
> p.bar.im_func.anotherattribute = 1
> print p.bar.anotherattribute # -> 1
>
> (the attribute must be set on the *function* itself if you want it to be
> somewhat persistent; methods are usually volatile objects)
You read my mind.
I was just getting:
assert p.bar is p.bar
and failing.
But if you set them on im_func, instances don't have their own.
More information about the Python-list
mailing list