简体   繁体   中英

Calling base class method from instance creating using type function

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?

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM