Skip to content

Instantly share code, notes, and snippets.

@balu
Last active February 15, 2021 07:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save balu/210d20747e5cf3f0295fa259a3f3ca14 to your computer and use it in GitHub Desktop.
Save balu/210d20747e5cf3f0295fa259a3f3ca14 to your computer and use it in GitHub Desktop.

Introduction

If your program needs to define a new kind of values, use a class. Follow the below steps to define a class.

  1. Come up with a good name for the type.
  2. Determine the components and their types.
  3. Write a __init__ function that initializes the components of the type appropriately from the arguments. This may involve complex logic.

To write functions that operate on your new type, follow the same instructions as for tuples. Instead of unpacking, you may use . to access the components.

Exercises

  1. Write a class to represent the shape circle. Define operations to compute the area and perimeter on values of this new type.

  2. Change the definition of Circle so that it now represents circles in the two-dimensional plane. i.e., it should now incorporate origin into the definition.

  3. Write a function that takes two circles as input and determines whether they overlap. What is the appropriate return type? How can you determine whether two circles overlap?

  4. Write a function to create a Point from polar co-ordinates.

  5. Define an operation to add two Rational numbers.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment