TypeError for Unbound Method in Python Class and Factory Method

Question:

So, I have a class, where a class variable is set to the output from a class factory in the __init__ method, like so:

def MyFooFactory():
    def __init__(self, *args):
        # Do __init__ stuff

    def MyBar(myFoo_obj):
        print "MyBar"

    newclass = type("MyFoo", tuple(object), {"__init__": __init__, "MyBar": MyBar} )
    return newclass

class Foo:
    Bar = 0
    def __init__(self):
        if (type(Foo.Bar) is int):
            Bar = MyFooFactory()

    def MyBar(a_list):
        for l in a_list:
            Bar.MyBar(l)

However, when I try this

myBar_list = [Foo.Bar() for _ in range(x)]
Foo.MyBar(myBar_list)

TypeError: unbound method MyBar() must be called with Foo instance as first argument (got list instead)

Is this happening because MyBar has the same name in both Foo and MyFoo or is there something else afoot here?

For reference, both MyBar methods are supposed to be unbound.

Thanks,

Asked By: Woody1193

||

Answers:

It’s because you forgot self parameter in MyBar

Try this:

class Foo:
    ...

    def MyBar(self, a_list):
        for l in a_list:
            Bar.MyBar(l)

If it’s supposed to be “unbound” method use @staticmethod decorator:

Answered By: Aleksandr Kovalev

The statement

Bar = MyFooFactory()

is assigning a local, not the class-level Bar member that is called in Foo.MyBar

If you want to assign that inside a method the syntax is

Foo.Bar = MyFooFactory()

Scope rules inside the class body are somewhat surprising.

Answered By: 6502

Instance methods in Python must have self as first argument (where self is really just a formal parameter name like any other – it gets bound to the instance by virtue of being the first one), so you’d have

def MyBar(self, a_list):
    ...

On the other hand, if you did want a static method you’d have to use the @staticmethod decorator:

@staticmethod
def MyBar(a_list):
    ...

See also this answer: What is the difference between @staticmethod and @classmethod in Python?

Answered By: Tobia Tesan
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.