类可以检测正在实例化的对象的名称

时间:2017-02-15 17:13:16

标签: python python-3.x class object

我想让一个类在实例化时自动记录该类的所有对象,因此,给出这段代码:

class Comet:
    comets = []

    __init__(self, mass):
        self.mass = mass
        Comet.comets.append(**instance name as a string**)


HalleysComet = Comet(3*10**14)
Temple 1 = Comet(7.9*10**13)

print(str(Comet.comets))

输出将是:

['HalleysComet', 'Temple 1']

0 个答案:

没有答案