使用母类属性初始化实例

时间:2016-07-26 15:01:48

标签: python class inheritance

我正在处理使用astropy lib中的fits.open()读取的拟合文件。我得到一个hdu(标题数据单元),它是astropy.io.fits.hdu.image.PrimaryHDU的一个实例。

现在,对于一个特定的项目,我想通过编写特定的方法来处理这个hdu中的数据。我认为,这样做的好方法是编写我自己的类,它将成为PrimaryHDU的子类。我的新对象将具有PrimaryHDU实例的所有属性和方法,以及我将编写的属性和方法。但我不能让它正常工作。我的新对象如何获取父对象的所有属性和方法?我最接近的是使用以下代码(例如,新方法调用“减去”):

from astropy.io.fits.hdu.image import PrimaryHDU

class MyHDU(PrimaryHDU):

    def __init__(self, hdu):
        PrimaryHDU.__init__(self, data=hdu.data, header=hdu.header)

    def subtract(self, val):
        self.data = self.data - val

有点好,但我可以看到我的新对象没有将所有属性设置为与原始对象(hdu)相同的值....这看起来很正常,当我查看我的代码时实际上......但是如何用父对象的所有属性初始化我的新对象?我是否正确使我的新类继承自PrimaryHDU类? 感谢

1 个答案:

答案 0 :(得分:0)

  

如何使用父对象的所有属性初始化我的新对象?

你不能。你不是从一个实例(即对象)继承,而是从一个类继承。

你应该做的是传递你需要的所有参数,以便初始化父类和子类。在子类的__init__方法调用super().__init__(父类的__init__方法)中,然后初始化子类的其余部分:

from astropy.io.fits.hdu.image import PrimaryHDU

class MyHDU(PrimaryHDU):

    def __init__(self, args_to_init_PrimaryHDU_obj, hdu):
        super().__init__(args_to_init_PrimaryHDU_obj)
        # if using Python 2 the above line should be
        # super(PrimaryHDU, self).__init__(args_to_init_PrimaryHDU_obj)
        self.data = hdu.data
        self.header = hdu.header

    def subtract(self, val):
        self.data = self.data - val
相关问题