LoginSignup
6
5

More than 5 years have passed since last update.

Pythonの古いクラスと新しいクラスの話

Last updated at Posted at 2013-07-30

5年以上使ってもPython初心者のあめ玉です

で、ある本でこういう記載がありまして

class SomeClass(object):
  ..

この「object」ってなんですかね、と思ったので、メモ。

Python class inherits object(Stack Overflow)

Python2系だと2種類のクラスが存在し、新しい方でないと型に関する情報がぐっだぐだになる、という感じっぽいのです。Python3には新しい方しかないので、死にゆく知識の一つと思われます。

まぁ試してみます。結果から分かる愛ってのもあるよね

class_exp.py
class OldClass:
  def a(self):
    print("I'm OldClass")

class OldChild(OldClass):
  def a(self):
    super(OldChild, self).a()

class NewClass(object):
  def a(self):
    print("I'm NewClass")

class NewChild(NewClass):
  def a(self):
    super(NewChild, self).a()

x = OldChild()
y = NewChild()
print(type(x))
print(type(y))
print('--')
try:
  # Will fail with Python 2.x
  x.a() 
except TypeError as e:
  import traceback
  traceback.print_exc()
print('--')
y.a()
> python2.7 misc/class_exp.py
<type 'instance'>
<class '__main__.NewChild'>
--
Traceback (most recent call last):
  File "misc/class_exp.py", line 27, in <module>
    x.a()
  File "misc/class_exp.py", line 10, in a
    super(OldChild, self).a()
TypeError: must be type, not classobj
--
I'm NewClass

> python3.2 misc/class_exp.py
<class '__main__.OldChild'>
<class '__main__.NewChild'>
--
I'm OldClass
--
I'm NewClass

Python2では古い方のクラスのオブジェクトは型が期待した通りに見えてません。type(obj) の結果で ``'' となっている点に一つポイントがあるようです。その関係なんですかね、super() で正しく親クラスを見れていません。

あとは昔のドキュメントを読んでください。

(2 PEPs 252 and 253: Type and Class Changes)[http://docs.python.org/release/2.2.3/whatsnew/sect-rellinks.html]

ところで冒頭のとある本はPython3をメインに据えた本とのことで、なんでPython3では必要のないobjectを明示的に指定したのかについては、よくわかりません。

6
5
0

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
6
5