python - How can I create bound methods with type()? -


I am dynamically building a function and specifying it in a class. This is a simple / minimal example of what I am trying to achieve:

def echo (obj): print obj.hello class Foo (object): Hello = "Hello World" Spam = type ("spam", (foo), {"echo": echo}} spam.echo ()

results in this error

  Traceback (most recent call final): File "& lt; Input>", line 1, & lt; Module & gt; TypeError: The unbound method should go with the echo () spam instance as the first argument (instead of nothing)  

I know whether I @staticmethod Decorator I can pass spam as a parameter for echo, but in my case for use it is not possible for me.

How do I get the echo function to be bound to spam and go to self ? Is this possible?

So far, you have created only one category Spam = Type ("Spam", (Foo,) , {"Echo": echo}} Spam = Spam () For spam, you need to create an object, for example:

 .echo ()  

If you really want to become a method on class instead of an example method, then wrap it with classmethod (instead of staticmethod).


Comments

Popular posts from this blog

c# - ListView onScroll event -

PHP - get image from byte array -

Linux Terminal Problem with Non-Canonical Terminal I/O app -