我不想在从子 class 添加属性时不必重新指定对象的父属性

I want to not have to respecify parent attributes of an object when adding attributes from a child class

所以我有这个星星数据集,我正在为 (Star) 创建 class。在这些恒星中,有些是变星。我创建了一个子 class(变量),但是当我确定我的一个 Star 对象是一个变星(代码不包括在内)时,我想在同一个对象中包含额外的信息而不必重新指定旧信息,并将对象进一步分类为子对象 class.

我知道如果我这样做就可以让它工作:

# Class attribute
category = 'variable'

# Initializer / Instance attributes
def __init__(self, name, coordinates, scatter, photometry, periods, amplitudes):

然后:

star1 = Variable('Star 1', ('RA', 'dec'), 0.1, np.sin(np.linspace(0,1,100)), [1,100,1000], [1,2,1])

但我不想重新指定所有这些信息。

# Parent class
    class Star:

    # Class attribute
    category = 'TESS'

# Initializer / Instance attributes
def __init__(self, name, coordinates, scatter):
    self.name = name
    self.coordinates = coordinates
    self.scatter = scatter

star1 = Star('Star 1', ('RA', 'dec'), 0.1)
print('Parent class')
print('category    :', star1.category)
print('name        :', star1.name)
print('coordinates :', star1.coordinates)
print('scatter     :', star1.scatter, '\n')

# Child class (inherits from Star() class)
class Variable(Star):

    # Class attribute
    category = 'variable'

    # Initializer / Instance attributes
    def __init__(self, photometry, periods, amplitudes):
        self.photometry = photometry
        self.periods = periods
        self.amplitudes = amplitudes

star1 = Variable(np.sin(np.linspace(0,1,100)), [1,100,1000], [1,2,1])
print('Child class')
print('category   :', star1.category)
print('photometry :', star1.photometry)
print('periods    :', star1.periods)
print('amplitudes :', star1.amplitudes)

下面的代码按预期工作。但是,如果我尝试:

print(star1.name)

之后:

star1 = Variable(np.sin(np.linspace(0,1,100)), [1,100,1000] [1,2,1])

名称、坐标和散点似乎已从我的对象中删除。

必须调用superclass的初始化方法,否则永远不会运行!换句话说,Star class 的 __init__ 方法不会 运行 除非你告诉它。

class Variable(Star):
    def __init__(self, arg1, arg2):
        super().__init__(arg1)
        self.arg2 = arg2

super() 是访问 superclass 及其方法的一种方式。所以假设你在 Star class 中有一个 merge 方法合并了两颗星,你想从 Variable class 中调用它,你会调用super().merge(other_star).