2016-11-03 2 views
0

이 코드에서 생성자는 Sun이라는 다른 클래스에서 만든 태양의 이름을 묻는 것으로 시작합니다. Sun은 name, radius, mass 및 temp의 4 가지 속성을 가진 태양 객체를 만듭니다. 이 solarsystem 클래스에서 내가하려고하는 것은 모든 행성의 총 질량과 태양 객체의 질량을 계산하는 것이지만 Sun 클래스를 통해 생성 한 태양 객체의 속성에 어떻게 접근하는지에 대해 상당히 혼란 스럽습니다. 정말 좋은 설명을 발견하지 않았습니다 아직다른 클래스에서 하나의 클래스 객체 사용 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