old-style class
組み込み関数 super は、指定した属性値を獲得します。
##---------------------------------------- Python 2.1 class Parent: def __init__(self, name): self.name = name def __str__(self): return "%s"%self.name def show(self): return "My name is %s"%( self.name)
親クラスを指定しないと、そのクラスを頂点とする、新たなクラス階層が形成されます。
class Child(Parent): def __init__(self, name, age): Parent.__init__(self, name) self.age = age def __str__(self): return "%s, %d"%( Parent.__str__(self), self.age) def show(self): return "%s, and I'm %d years old"%( Parent.show(self), self.age)
親クラスのメソッドを呼び出すときには、そのクラス Parent を指定する必要があります。以下のコードを実行すると、
print "-"*40,"Python 2.1" e = Parent("Jonh Doe") print e; print e.show() e = Child("Jane Doe", 23) print e; print e.show()
次のような出力が得られます。
---------------------------------------- Python 2.1 Jonh Doe My name is Jonh Doe Jane Doe, 23 My name is Jane Doe, and I'm 23 years old