【问题标题】:I want to not have to respecify parent attributes of an object when adding attributes from a child class从子类添加属性时,我不想重新指定对象的父属性
【发布时间】:2019-08-26 20:44:16
【问题描述】:

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

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

# 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])

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

【问题讨论】:

标签: python-3.x class object parent-child


【解决方案1】:

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

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

super() 是访问超类及其方法的一种方式。因此,假设您在 Star 类中有一个 merge 方法,它合并了两个星,并且您想从 Variable 类中调用它,您可以调用 super().merge(other_star)

【讨论】:

  • 当我将star1重新分类为变星时,我仍然需要指定星星的名称、坐标和散布。
  • 是的,因为要制作星形,您已经声明用户需要传入名称、坐标和散点图。所以在某些时候你必须指定这些变量是什么。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-12
  • 1970-01-01
相关资源
最近更新 更多