2016-11-03 2 views
0

このコードでは、コンストラクタはSunと呼ばれる別のクラスから作成された太陽の名前を尋ねることから開始します。 Sunは、name、radius、mass、およびtempの4つの属性を持つsunオブジェクトを作成します。私がこのソラールシステムクラスでやろうとしているのは、すべての惑星の総質量に太陽オブジェクトの質量を加えたものですが、サンクラスで作成した太陽オブジェクトの属性にどのようにアクセスするのかはかなり混乱しています。本当に良い説明を見つけていない、まだ別のクラスで1つのクラスオブジェクトを使用する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

、私はちょうどtotalMass、ないmassを使用するtotalMass()print文を変更する必要がありました:

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

関連する問題