0

I'm writing a class that is supposed to represent a parallelogram, the attributes are sideAB, sideDA and angleA, angleA has 90 as its default value the default value of sideDA is supposed to be the same as sideAB, I'm not sure how to implement this. This is what I tried

class Quad( object ):

def __init__( self, AB, DA=AB, A=90 ):


    self.sideAB = AB
    self.sideDA = DA
    self.angleA = A

I get the error: name 'AB' is not defined, which makes sense. Any help would be appreciated

B _____C

A|_____|D

tried to draw the sides, I hope is helpful

  • May be drawing of ABCD would be helpful. I am thinking you mean opposite side should be equal and two parameters are enough for parallelogram as opposite sides are parallel and equal? – niraj Jun 14 '20 at 02:09
  • DA is the sext side is done like this so if i enter just one value i would get a square – Marcelo Rebaza Bartra Jun 14 '20 at 02:12

1 Answers1

2

The other parameters are only accessesible from within the function definition (so you cannot have a default parameter DA=AB). One way to handle this is to default to None, then have a special interpretation of None within the function.

class Quad:
    def __init__(self, AB, DA=None, A=90):
        self.sideAB = AB
        self.sideDA = AB if DA is None else DA
        self.angleA = A

square = Quad(10)
rect = Quad(10,20)
rhombus = Quad(10,A=30)
parallelogram = Quad(10,20,30)
anjsimmo
  • 704
  • 5
  • 18
  • 1
    Can also change `DA if DA is not None else AB` to `AB if DA is None else DA` to get rid of the `not`. – Mario Ishac Jun 14 '20 at 02:19
  • Thanks a lot! I didn't know it was possible to write an "if" like that, I'll try it – Marcelo Rebaza Bartra Jun 14 '20 at 02:22
  • @Mario Ishac Thanks for the suggestion! I've updated my answer. – anjsimmo Jun 14 '20 at 02:22
  • 2
    More to the point, the default value is computed *ahead of time* and bound within the function object. `DA=AB` tries to use the value of `AB` at the time that the `def` is encountered, before it ever gets called. See also: https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument , which is another consequence of determining the value ahead of time. – Karl Knechtel Jun 14 '20 at 02:33