[Baypiggies] bound and unbound methods

Zachary Collins recursive.cookie.jar at gmail.com
Sun Jun 24 08:13:37 CEST 2012


Woah.  Dude, it's just a function.  Why would you need to transform it
to a bound method anyways?  How about,

meth_cell(self, gunk)

?  Afterall, look at your method signatures.  A method is just a
function that takes an instance as its first argument (remember, and
you even called it "self" right?)

2012/6/23 Simeon Franklin <simeonf at gmail.com>:
> What version of Python are you using? The code below does work exactly
> for me (2.6.5 on my unbuntu box) - but it isn't really illustrating
> your question either. You have at class definition an existing class
> method aliased to a new name (the "meth_cell = meth" line). But "meth"
> will be a bound method of any instantiated objects and generally if
> you add regular old functions dynamically to your classes Python
> converts them to bound methods when making objects out of your class.
> As long as your function takes a first parameter representing self
> you're OK. So given your class I did
>
>>>> k = K()
>>>> k.another('asdf')
> asdf
>
> Everything seems to work. As to your question: If you have a function
> defined outside the class you can add it to the class later with
>
>>>> K.another_method = some_func
>
> and things will just work. If you want to add functions to objects,
> however, that's when things get tricky.
>>>> def foo(self):
> ...     print self
>>>> k = K()
>>>> k.foo = foo
>>>> k.foo()
> TypeError: foo() takes exactly 1 argument (0 given)
>>>> k.foo
> <function foo at 0x...>
>
> To attach a function to an object and convert it to a bound method
> import types and convert it manually to a bound method
>
>>>> k.foo = types.MethodType(foo, k, K)
>>>> k.foo
> <bound method K.foo of <__main__.K object at 0x989216c>>
>
> -regards
> Simeon Franklin
>
>
>
> On Fri, Jun 22, 2012 at 10:53 PM, Ian Zimmerman <itz at buug.org> wrote:
>>
>> Is there any semi-clean way to transform an unbound method into a bound
>> one?
>>
>> class K(object):
>>
>>      def meth(self, junk):
>>          print junk
>>
>>      meth_cell = meth
>>
>>      def another(self, gunk):
>>          # this doesn't work, what does?
>>          self.meth_cell(gunk)
>>
>> --
>> Ian Zimmerman
>> gpg public key: 1024D/C6FF61AD
>> fingerprint: 66DC D68F 5C1B 4D71 2EE5  BD03 8A00 786C C6FF 61AD
>> http://www.gravatar.com/avatar/c66875cda51109f76c6312f4d4743d1e.png
>> Rule 420: All persons more than eight miles high to leave the court.
>> _______________________________________________
>> Baypiggies mailing list
>> Baypiggies at python.org
>> To change your subscription options or unsubscribe:
>> http://mail.python.org/mailman/listinfo/baypiggies
> _______________________________________________
> Baypiggies mailing list
> Baypiggies at python.org
> To change your subscription options or unsubscribe:
> http://mail.python.org/mailman/listinfo/baypiggies


More information about the Baypiggies mailing list