tags:

views:

64

answers:

1

I am dynamically generating a function and assigning it to 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 last):
File "<input>", line 1, in <module>
TypeError: unbound method echo() must be called with Spam instance
    as first argument (got nothing instead)

I know if I used the @staticmethod decorator that I can pass spam in as a parameter to echo, but that is not possible for me in my use case.

How would I get the echo function to be bound to Spam and access self? Is it possible at all?

+8  A: 

So far, you only have created a class. You also need to create objects, i.e. instances of that class:

Spam = type("Spam", (Foo, ), {"echo":echo})
spam = Spam()
spam.echo()

If you really want this to be a method on the class, rather than an instance method, wrap it with classmethod (instead of staticmethod).

Martin v. Löwis