Difference between 'function' and 'method'

castironpi at gmail.com castironpi at gmail.com
Tue Mar 4 23:02:46 EST 2008


On Mar 4, 9:53 pm, castiro... at gmail.com wrote:
> > >> >> 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.

class myfunction:
    __slots__ = ('func','name')
    #
    def __init__(self, func):
      object.__setattr__(self, 'func', func)
      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(self, x): print( 'bar',x )

p= P()
p.foo( 0 )
p.bar( 1 )
print( p.bar )
print( p.bar.name )

'''
output:
'''
foo 0
__get__ called for <__main__.P object at 0x00B481F0>
bar 1
__get__ called for <__main__.P object at 0x00B481F0>
<bound method P.bar of <__main__.P object at 0x00B481F0>>
__get__ called for <__main__.P object at 0x00B481F0>
bar



More information about the Python-list mailing list