【发布时间】: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