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

本文探讨Python编程中如何创建类、实现父子类的继承,并重点讲解如何在子类中调用父类的构造函数__init__。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值