2011-08-15 3 views
4

CS-600 용 MIT 오픈 코스웨어에서 작업하고 있는데 마지막 인쇄 문이 왜 아무 것도 인쇄하지 않는 이유를 알 수 없습니다.내 main 메서드의 맨 아래에있는 print 문이 아무 것도 인쇄하지 않는 이유는 무엇입니까?

#!/usr/bin/env python 
# encoding: utf-8 
# 6.00 Problem Set 9 
# 
# Name: 
# Collaborators: 
# Time: 

from string import * 

class Shape(object): 
    def area(self): 
     raise AttributeException("Subclasses should override this method.") 

class Square(Shape): 
    def __init__(self, h): 
     """ 
     h: length of side of the square 
     """ 
     self.side = float(h) 
    def area(self): 
     """ 
     Returns area of the square 
     """ 
     return self.side**2 
    def __str__(self): 
     return 'Square with side ' + str(self.side) 
    def __eq__(self, other): 
     """ 
     Two squares are equal if they have the same dimension. 
     other: object to check for equality 
     """ 
     return type(other) == Square and self.side == other.side 

class Circle(Shape): 
    def __init__(self, radius): 
     """ 
     radius: radius of the circle 
     """ 
     self.radius = float(radius) 
    def area(self): 
     """ 
     Returns approximate area of the circle 
     """ 
     return 3.14159*(self.radius**2) 
    def __str__(self): 
     return 'Circle with radius ' + str(self.radius) 
    def __eq__(self, other): 
     """ 
     Two circles are equal if they have the same radius. 
     other: object to check for equality 
     """ 
     return type(other) == Circle and self.radius == other.radius 

# 
# Problem 1: Create the Triangle class 
# 
## TO DO: Implement the `Triangle` class, which also extends `Shape`. 

class Triangle(Shape): 
    def __init__(self, base, height): 
     self.base = float(base) 
     self.height = float(height) 
    def area(self): 
     return self.base*self.height/2 
    def __str__(self): 
     return 'Triangle with base ' + str(self.base) + 'and height ' + str(self.height) 
    def __eq__(self, other): 
     return type(other) == Triangle and self.base == other.base and self.height == other.height 
# 
# Problem 2: Create the ShapeSet class 
# 
## TO DO: Fill in the following code skeleton according to the 
## specifications. 

class ShapeSet(object): 
    def __init__(self): 
     """ 
     Initialize any needed variables 
     """ 
     self.allCircles = [] 
     self.allSquares = [] 
     self.allTriangles = [] 
     self.allShapes = self.allCircles + self.allSquares + self.allTriangles 
     self.place = None 
    def addShape(self, sh): 
     """ 
     Add shape sh to the set; no two shapes in the set may be 
     identical 
     sh: shape to be added 
     """ 
     if not isinstance(sh, Shape): raise TypeError('not a shape') 
     if isinstance(sh, Square): 
      for sq in self.allSquares: 
       if sh == sq: 
        raise ValueError('shape already in the set') 
      self.allSquares.append(sh) 
     if isinstance(sh, Triangle): 
      for tri in self.allTriangles: 
       if sh == tri: 
        raise ValueError('shape already in the set') 
      self.allTriangles.append(sh) 
     if isinstance(sh, Circle): 
      for circ in self.allCircles: 
       if sh == circ: 
        raise ValueError('shape already in the set') 
      self.allCircles.append(sh) 
    def __iter__(self): 
     """ 
     Return an iterator that allows you to iterate over the set of 
     shapes, one shape at a time 
     """ 
     self.place = 0 
     return self 
    def next(self): 
     if self.place >= len(self.allShapes): 
      raise StopIteration 
     self.place += 1 
     return self.allShapes[self.place - 1] 

    def __str__(self): 
     """ 
     Return the string representation for a set, which consists of 
     the string representation of each shape, categorized by type 
     (circles, then squares, then triangles) 
     """ 
     shapeList = "" 
     for item in self.allShapes: 
      shapeList += item.get__str__ + "br/" 
     return shapeList 

# 
# Problem 3: Find the largest shapes in a ShapeSet 
# 
def findLargest(shapes): 
    """ 
    Returns a tuple containing the elements of ShapeSet with the 
     largest area. 
    shapes: ShapeSet 
    """ 
    ## TO DO 

# 
# Problem 4: Read shapes from a file into a ShapeSet 
# 
def readShapesFromFile(filename): 
    """ 
    Retrieves shape information from the given file. 
    Creates and returns a ShapeSet with the shapes found. 
    filename: string 
    """ 
    ## TO DO 

def main(): 
    sq1 = Square(4.0) 
    sq2 = Square(5.0) 
    sq3 = Square(3.0) 
    circ1 = Circle(3.0) 
    circ2 = Circle(3.2) 
    tri1 = Triangle(3.0, 4.0) 
    tri2 = Triangle(4.0, 3.0) 
    tri3 = Triangle(1.0, 1.0) 
    thisSet = ShapeSet() 
    thisSet.addShape(sq1) 
    thisSet.addShape(sq2) 
    thisSet.addShape(sq3) 
    thisSet.addShape(circ1) 
    thisSet.addShape(circ2) 
    thisSet.addShape(tri1) 
    thisSet.addShape(tri2) 
    thisSet.addShape(tri3) 
    print thisSet 



if __name__ == '__main__': 
    main() 

답변

1

이 줄 allShapes에게 빈 목록을 만드는 : 당신이 allCircles을 수정하는 경우, allShapes에 영향을주지

self.allShapes = self.allCircles + self.allSquares + self.allTriangles 

. 나는 개인적으로 allShapes을 제거하고, STR 방법, 마지막 가능한 초에 추가 할 것 : self.allCircles + self.allSquares + self.allTriangles의

for item in self.allCircles + self.allSquares + self.allTriangles: 
6

이 행 :

self.allShapes = self.allCircles + self.allSquares + self.allTriangles 

당신이 그것을하지 생각하지 않습니다 여기에 내가 쓴 코드입니다. allShapes을 빈 목록으로 설정하면 나중에 모양을 추가 할 때 아무 것도 allShapes을 업데이트하지 않습니다.

__str__ 함수는 여전히 비어있는 allShapes을 반복합니다. 따라서 __str__은 빈 문자열을 반환합니다. 이 실제 코드의 경우

0

, 그것은해야합니다 예외가 발생한다

item.get__str__ 

때문에

.

편집 : : 다른 사람이 지적했듯이, 이것은 실제 문제는 아니지만, 여기를 더 발전시키기위한 힌트로 남겨 두었습니다. 궁금하신 점이 있으시면 x.__str__()으로 직접 전화하는 것이 나쁜 스타일 ("unpythonic")으로 간주됩니다. 대신 __str__ 구현시 str(x)으로 전화하십시오.

0

당신은 allShapes를 할당 init 메소드의 시작 (다른 목록이 비어있는 경우)

값은 변경되지 않으므로 값은 비어 있습니다.

당신은 addShape이 필요합니다

self.allShapes.append(sh) 
1

문제는 여기에 있습니다 :이 같은 목록을 연결할 때

self.allShapes = self.allCircles + self.allSquares + self.allTriangles 

는, 결과는 구성 요소 목록의 사본입니다. 따라서 이러한 목록이 나중에 변경되면 연결된 목록은 변경되지 않습니다. 이 경우 self.allCircles 등은 모두 비어 있습니다. 따라서 self.allShapes도 빈 목록입니다. ShapeSet.__str__의 for 루프는 ShapeList에 아무 것도 추가하지 않으므로 결과는 빈 문자열입니다. 이 문제를 해결하는

하나의 간단한 방법은 전화가 allShapes방법 수 있도록하는 것, 그리고 등이 호출 할 때마다 self.allCircles의 새로운 연결을 ... 반환합니다. 그런 식으로 allShapes은 항상 최신입니다.

관련 문제