1

Normally, a base class method in Python can be called from a derived class the same way any derived class function is called:

class Base:
    def base_method(self):
        print("Base method")

class Foo(Base):
    def __init__(self):
        pass

f = Foo()
f.base_method()

However, when I create a class dynamically using the type function, I am unable to call base class methods without passing in a self instance:

class Base:
    def base_method(self):
        print("Base method")

f = type("Foo", (Base, object), { "abc" : "def" })
f.base_method() # Fails

This raises a TypeError: TypeError: base_method() takes exactly 1 argument (0 given)

It works if I explicitly pass a self parameter:

f.base_method(f)

Why is it necessary to explicitly pass the self instance when calling a base class method?

3
  • No sense having class Foo(Base):... in your second example. Commented Sep 12, 2012 at 19:11
  • Probably it'is a cut&paste error. Commented Sep 12, 2012 at 19:14
  • @Bakuriu -- Probably. I just thought I would point it out. Depending on exactly what OP thinks type does, he might believe that it is necessary there and that somehow f and the class Foo are related (since they have the same __name__ after all). Commented Sep 12, 2012 at 19:21

2 Answers 2

4

Your line f = type(...) returns a class, not an instance.

If you do f().base_method(), it should work.

Sign up to request clarification or add additional context in comments.

Comments

2

type return a class not an instance. You should instantiate the class before calling base_method:

>>> class Base(object):
...     def base_method(self): print 'a'
... 
>>> f = type('Foo', (Base,), {'arg': 'abc'})
>>> f.base_method()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unbound method base_method() must be called with Foo instance as first argument (got nothing instead)
>>> f().base_method()
a

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.