Thread: Class question

    #1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    9
    Rep Power
    0

    Class question


    Working from a text book the question reads “Implement a class Polygon that abstracts regular polygons and supports class methods:
    - __init__(): A constructor that takes as input the number of sides and the side length of a regular n~gon (n-sided polygon) object
    - perimeter(): Returns the perimeter of n-gon object
    - area(): Returns the area of the n-gon object
    To me this is a mouthful but I did my best with what little experience I have and what I have read from the text book I have and the below text is what I have so far.

    Any help would be greatly appreciated.
    Code:
    import math
    
    class Polygon:
        'Template for a mathematical shape.'
        def __init__(self,points=[(0,0),(0,0)]):
            pass # omitting other stuff
    
    class Rectangle(Polygon):
        'Resembles an axis-aligned rectangle'
        def __init__(self, x, y, width, height):
            super(Rectangle, self).__init__([(x,y),(x+width,y),(x+width,y+height),(x, y+height)])
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,889
    Rep Power
    481
    I think you're on the right track. The regular polygon class your book requests is a specialized polygon. To me regular polygon is a subclass of polygon.
    Code:
    '''
        Working from a text book the question reads "Implement a class Polygon that abstracts regular polygons and supports class methods:
        -	__init__(): A constructor that takes as input the number of sides and the side length of a regular n~gon (n-sided polygon) object
        -	perimeter(): Returns the perimeter of n-gon object
        -	area(): Returns the area of the n-gon object
    '''
    import math
    import pprint
    try:
        import tkinter
    except:
        raise ValueError('program runs with python3')
    
    TAU = 2*math.pi # http://www.youtube.com/watch?v=jG7vhMMXagQ
    
    class Polygon:
        'Template for a mathematical shape.'
        def __init__(self,points=[(0,0),(0,0)]):
            assert 1 < len(points)
            self.points = points
    
        def __str__(self):
            return pprint.pformat(self.points)
    
        def bounding_box(self):
            n = list(self.points[0][:])       # min
            x = n[:]                          # max
            for p in self.points:
                for (i,c,) in enumerate(p):
                    n[i] = min(n[i],c)
                    x[i] = max(x[i],c)
            return(n,x,)
    
        def draw_do_not_preserve_aspect_ratio(self):
            p = self.points
            (n,x,) = self.bounding_box()
            canvas = tkinter.Canvas(width = 200, height = 200)
            canvas.pack()
            m = [180.0/(x[i]-n[i])for i in range(len(n))]   # not safe against 0 denominator
            b = [10-n[i]*m[i]for i in range(len(n))]
            stp = []
            for p in self.points:
                for (i,c,) in enumerate(p):
                    stp.append(c*m[i]+b[i])
            canvas.create_polygon(*stp)
            canvas.update()
    
        def draw(self):
            p = self.points
            (n,x,) = self.bounding_box()
            n = min(n)
            x = max(x)
            canvas = tkinter.Canvas(width = 200, height = 200)
            canvas.pack()
            m = 180.0/(x-n)
            b = 10-n*m
            stp = []
            for p in self.points:
                for (i,c,) in enumerate(p):
                    stp.append(c*m+b)
            canvas.create_polygon(*stp)
            canvas.update()
    
    class RegularPolygon(Polygon):
    
        def __init__(self,number_of_sides,side_length=1):
            self.number_of_sides = number_of_sides
            self.side_length = side_length
            self.angle = TAU/number_of_sides
            self.radius = side_length/(2*math.asin(self.angle/2))
            r = self.radius
            cos = math.cos
            sin = math.sin
            n = number_of_sides
            Polygon.__init__(self,[(r*cos(i*TAU/n),r*sin(i*TAU/n))for i in range(n)])
    
    class Rectangle(Polygon):
        'Resembles an axis-aligned rectangle'
        def __init__(self, x, y, width, height):
            super(Rectangle, self).__init__([(x,y),(x+width,y),(x+width,y+height),(x, y+height)])
    If that code is in the file p.py
    Code:
    $ python3 -ic 'import p;pg=p.RegularPolygon(10)'
    >>> pg.draw()
    >>> p.Rectangle(0,0,200,500).draw()
    >>> print(str(pg))
    Last edited by b49P23TIvg; November 19th, 2012 at 06:47 PM.
    [code]Code tags[/code] are essential for python code and Makefiles!
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    9
    Rep Power
    0

    Thanks for you help


    Thanks for you help with this. I have to ask if all of that code is neccesary? I only ask because when I met with my study group we had a guest and he coded this in less than 20 lines. I am still very new to programming so I am happy to get multiple perspectives.

    Also.....

    When I type in the following commands i get an error.
    >>>p2 = Polygon(6, 1)
    p2.perimeter()

    Again thanks for you help.
    Code:
    p2 = Polygon(6, 1)
  6. #4
  7. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,889
    Rep Power
    481
    My program neither calculates area nor perimeter. It draws polygons, scaling and translating to fit into a window. Therefor I'd say that just about none of my code is necessary.

    I didn't change the interface to the constructor for your Polygon class. As you'll recall you presented
    def __init__(self,points=[(0,0),(0,0)]):
    The example says that points should be a list.

    Now you complain that when you use
    Polygon(6, 1)
    you get an error. Surprise surprise!

    My code demonstrated merely that your concept for a base Polygon class could be useful in defining the regular polygon of the problem statement.

    Did you see the example use code at the very end of my post?
    [code]Code tags[/code] are essential for python code and Makefiles!
  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    9
    Rep Power
    0

    Thanks


    Since I am new to this I tend not to ask the questions incorrectly. The code I originally posted was way off base.
    With that said, how would you code the following?

    Implement a class Polygon that abstracts regular polygons and supports class methods:
    - __init__(): A constructor that takes as input the number of sides and the side length of a regular n~gon (n-sided polygon) object
    - perimeter(): Returns the perimeter of n-gon object
    - area(): Returns the area of the n-gon object
    Code:
    class Polygon:
  10. #6
  11. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,889
    Rep Power
    481

    Recognize a master of the double negative.


    Code:
    class Polygon(object):
    
        '''
            >>> 4 == Polygon(4).perimeter()
            True
        '''
    
        def __init__(self,sides,edge_length=1):
            self.sides = sides
            self.edge_length = edge_length
    
        def area(self):
            print('computing area...')
            result = 0
            # your difficult algebraic computation here
            return result
    
        def perimeter(self):
            return self.edge_length*self.sides
    
        def hydraulic_diameter(self):
            return 4*self.area/self.perimeter
    
        def __str__(self):
            return "Where'd Poly go?"
    Last edited by b49P23TIvg; November 21st, 2012 at 01:12 PM.
    [code]Code tags[/code] are essential for python code and Makefiles!
  12. #7
  13. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    9
    Rep Power
    0
    What is the meaning of the @property? Also, I am new to this and appreciate you patience with me!
    Code:
    @property
  14. #8
  15. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,889
    Rep Power
    481
    Never mind the property. It was incorrect since your instructions say to use the method with argument list. I edited the prior post accordingly.
    [code]Code tags[/code] are essential for python code and Makefiles!

IMN logo majestic logo threadwatch logo seochat tools logo