python中类的创建,父子类的继承

来源:互联网 发布:西安星河网络小贷 编辑:程序博客网 时间:2024/05/19 22:27
#!/usr/bin/pythonclass 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/pythonclass 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__

则两种调用父类构造器的方法都可以,参考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()



0 0
原创粉丝点击