2016-11-03 177 views
0

在此代码中,构造函数首先要求从另一个称为Sun的类创建的太阳名称。 Sun创建一个具有4个属性的太阳物体:名称,半径,质量和温度。我在这个太阳系课程中试图做的是计算所有行星的总质量加上太阳物体的质量,但是我对如何访问通过太阳类创建的太阳物体的属性感到困惑。还没有真正找到一个很好的解释却在另一个类中使用一个类对象PYTHON

我的代码如下:

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

下面的代码对我的作品,我不得不改变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() 
+1

感谢我一直在想我以错误的方式调用类对象。我确实找到了编写代码的更好方法。 self.thesun.mass – Gonjirou

+0

乐意提供帮助,请记住接受我的回答,以便在他们尝试提供帮助时,人们不会将此视为未回答的问题。此外,您可以使用代字符键(\')来创建单行代码片段,例如:'self.thesun.mass',它可以更容易阅读。 – Darkstarone

相关问题