LoginSignup
7
8

More than 5 years have passed since last update.

Python で継承 しようとして TypeError: must be type, not classobj と言われてつらかった思い出

Last updated at Posted at 2016-05-07

Python で継承しようとして super と init したけど、
TypeError: must be type, not classobj
とか言われてつらかった時の思い出

まず、Pythonのバージョン

shell
$ python -V
Python 2.7.10

以下のクラスを継承して、別のクラスを作ろうとしていた。
継承元クラス

hogehoge.py
class Client():
    def __init__(self, url, **kwargs):

継承先クラス

manager.py
import hogehoge

class Manager(hogehoge.Client):
    def __init__(self, url, *kwargs):
        super(Manager,self).__init__(url, *kwargs)

使ってみる

shell
$ python
>>> import manager
>>> cl = manager.Manager("https://example.jp")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "manager.py", line 10, in __init__
    super(Manager,self).__init__(url, *kwargs)
TypeError: must be type, not classobj

ググってもよくわからなかった。

最終的にたどり着いたstackoverflowが以下。

python - super() raises "TypeError: must be type, not classobj" for new-style class - Stack Overflow
http://stackoverflow.com/questions/9698614/super-raises-typeerror-must-be-type-not-classobj-for-new-style-class

??オブジェクトに新しいのと古いのがある??
Pythonの型とクラスの関係については以下参照

python の型とクラスの関係 — ぱいそんにっき
http://pydiary.bitbucket.org/blog/html/2013/10/12/type.html

Pythonには、2種類のクラス オブジェクト がある。

  1. classobj
  2. type

上記の hogehoge.py で作られているインスタンスは、古い classobj で type ではないので、super できないよ。というエラーのようだ。

解決策は以下。継承先クラスで 親クラスを object として読み込む
Clientとobjectの両方を多重継承する
@shiracamus さんありがとうございます。

manager.py
import hogehoge

class Manager(hogehoge.Client, object):
    def __init__(self, url, *kwargs):
        super(Manager,self).__init__(url, *kwargs)

Python 初心者なので間違いなどあればご指摘ください。

7
8
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
8