pythonでのクラスの作成、親子クラスの継承
2071 ワード
#!/usr/bin/python
class Ppoint:
def __init__(self, x, y):
self.x = x
self.y = y
# def __del__(self):
# class_name = self.__class__.__name__
# print class_name, "destroyed"
class Spring_Point(Ppoint):
def __init__(self):
Ppoint.__init__(self, 1, 2)
# super(Spring_Point, self).__init__(1, 2)
if __name__ == "__main__":
xx = Spring_Point()
print xx.__dict__
以上、oldでclass,Ppoint,class Spring_を作成しました.Point Spring_の継承Point親クラスのコンストラクション関数を呼び出す場合は、
Ppoint.__init__(self, 1, 2)
使用不可
super(Spring_Point, self).__init__(1, 2)
心得を使用してクラスを作成する場合#!/usr/bin/python
class Ppoint(object):
def __init__(self, x, y):
self.x = x
self.y = y
# def __del__(self):
# class_name = self.__class__.__name__
# print class_name, "destroyed"
class Spring_Point(Ppoint):
def __init__(self):
Ppoint.__init__(self, 1, 2)
# super(Spring_Point, self).__init__(1, 2)
if __name__ == "__main__":
xx = Spring_Point()
print xx.__dict__
親コンストラクタを呼び出す方法の2つを参照してください.http://stackoverflow.com/questions/9698614/super-raises-typeerror-must-be-type-not-classobj-for-new-style-class
In short, they are equivalent. Let's have a history view:
(1) at first, the function looks like this.
class MySubClass(MySuperClass):
def __init__(self):
MySuperClass.__init__(self)
(2) to make code more abstract (and more portable). A common method to get Super-Class is invented like:
super(<class>, <instance>)
And init function can be:
class MySubClassBetter(MySuperClass):
def __init__(self):
super(MySubClassBetter, self).__init__()
However requiring an explicit passing of both the class and instance break the DRY (Don't Repeat Yourself) rule a bit.
(3) in V3. It is more smart,
super()