Student Login

Objectifying your brain

Reader Gautam - or "Groovy G", as I like to call him - asks:

"My brain thinks in functions, how do I push it to think in classes and objects?"

Great question, Groovy.

I could write a book about it. But I'll bottom line that book in five words:

Think in terms of TYPES.

You're just making a little switch here. Because when you code in functions, you're already thinking in terms of types - like int, and float, and list, and so on. Whatever those functions return, and operate on.

When you create a class, you're creating a new TYPE. A new structure of data. And the operations that are specific to it.

Just like int. "int" is a built-in type, holding data that are whole numbers.

And the operations you can do on them, like addition, and subtraction, and so on.

Or with list, you can do concatenation, slicing, etc.

Consider this:

  1. import math
  2. from dataclasses import dataclass
  3. @dataclass
  4. class Point:
  5. x: float
  6. y: float
  7. def __add__(self, other):
  8. 'Add two points.'
  9. return Point(self.x + other.x, self.y + other.y)
  10. def __mul__(self, factor):
  11. return Point(self.x * factor, self.y * factor)
  12. def distance(self, other):
  13. return math.sqrt((self.x-other.x)**2 + (self.y-other.y)**2)

Point is a new type. In Python, classes and types are the same - there's no difference, unlike with other languages.

The structure of Point is just barely more complex than int: two whole numbers, instead of one.

What operations will the Point type need?

You want to add two points together. That's what __add__ does.

You want to multiply it times a scalar - not by another Point, because that doesn't make sense for this type. Mathematically, the "*" operation is a mapping from a Point-number pair, to another Point.

Both __add__ and __mul__ hook into Python's built-in operators (look up "magic methods" if that's new to you).

But another operation that makes sense for the Point type is measuring distance between two points...

So we have a distance *method* for that.

A method is just an operator for a type. Sometimes it has side effects, sometimes not.

There's other ways to think about classes and objects. But if your brain tends to think in functions, like my pal Groovy here...

Start thinking of classes as types, just like functions return values of different types. That'll open the door, to a whole lot more.

White Paper Bootcamp