Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Use types.MethodType for that:

    >>> import types
    >>> 
    >>> def hello(self):
    ...     print self.name
    ... 
    >>> class Foo(object):
    ...     name = 'blah'
    ... 
    >>> goo = Foo()
    >>> goo.hi = types.MethodType(hello, Foo)
    >>> 
    >>> goo.hi()
    blah
Edit: pre-2.6 you'd use "new.instancemethod()"


Yes, or alternatively I believe

    In [27]: class Foo(object):
    ....:     pass
    ....: 
 
    In [28]: def hello(self):
    ....:     print self
    ....: 

    In [29]: blah = Foo()

    In [30]: blah.hello = hello.__get__(blah, Foo) 

    In [31]: blah.hello()
    <__main__.Foo object at 0x10397f650>




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: