在此代码中,构造函数首先询问从另一个名为Sun的类创建的sun的名称。 Sun创建一个具有4个属性的sun对象:name,radius,mass和temp。我想在这个solarsystem类中尝试做的是计算所有行星的总质量加上太阳对象的质量,但我对如何访问我通过Sun类创建的sun对象的属性感到困惑。还没有真正找到一个好的解释
我的代码如下:
class SolarSystem:
def __init__(self, asun):
self.thesun = asun
self.planets = []
def addPlanet(self, aplanet):
self.planets.append(aplanet)
def showPlanet(self):
for aplanet in self.planets:
print(aplanet)
def numPlanets(self):
num = 0;
for aplanet in self.planets:
num = num + 1
planets = num + 1
print("There are %d in this solar system." % (planets))
def totalMass(self):
mass = 0
sun = self.thesun
sunMass = sun.mass
for aplanet in self.planets:
mass = mass + aplanet.mass
totalMass = mass + sunMass
print("The total mass of this solar system is %d" % (mass))
答案 0 :(得分:0)
以下代码适用于我,我只需更改print
中的totalMass()
语句即可使用totalMass
,而不是mass
:
class SolarSystem:
def __init__(self, asun):
self.thesun = asun
self.planets = []
def addPlanet(self, aplanet):
self.planets.append(aplanet)
def showPlanet(self):
for aplanet in self.planets:
print(aplanet)
def numPlanets(self):
num = 0;
for aplanet in self.planets:
num = num + 1
planets = num + 1
print("There are %d in this solar system." % (planets))
def totalMass(self):
mass = 0
sun = self.thesun
sunMass = sun.mass
for aplanet in self.planets:
mass = mass + aplanet.mass
totalMass = mass + sunMass
print("The total mass of this solar system is %d" % (totalMass))
class Sun:
def __init__(self, name, radius, mass, temp):
self.name = name
self.radius = radius
self.mass = mass
self.temp = temp
test_sun = Sun("test", 4, 100, 2)
test_solar_system = SolarSystem(test_sun)
test_solar_system.totalMass()