2016-11-03 116 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

相關問題