#!/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__
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__
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()