class: a template for creating an object
We've defined instance and method. For this week's #TerminologyTuesday, it's finally time to define the word "class" in #Python. ππ
Where do classes come up and how do they work? π€
The terms "class" and "type" are synonyms in Python.
The type of an object is its class and an object's class is a "type".
As we discussed when we defined "class instance" last week, every object in Python has a class. That means classes are EVERYWHERE in Python.
list, dict, int, str, tuple, bool, set, and float are all classes.
But (somewhat strangely) range, enumerate, zip, reversed, and type are also classes. π¦ Huh?
We often don't care whether an object is a class or a function in Python. Both are callables. π
When you call a function, the function runs and you get back the return value of that function.
When you call a class, a new class instance is constructed, initialized, and returned to you.
So in Python, we often don't care whether a callable is a class or a function...
As long as we know how to work with the return value of a callable, whether the callable is a class or a function is just an implementation detail.
We do *sometimes* care whether a variable points to a class or function, but not often.
So classes are everywhere. And classes (like functions) are callables.
But what are they for?
Classes are most often used for coupling state and functionality.
Instead of passing a dictionary of values into many functions, we can make a class instance and call methods on it.
Wondering what a method is?
I defined that term a couple weeks ago.
Essentially a method is a function that's defined on a class and meant to operate specifically on instances of that class.
Class instances store data. And classes typically have methods that operate on that data.
Though classes are sometimes used *just* for their data.
If you're making a class *just* for its data, you may want to look into dataclasses.
pym.dev/dataclasses/
Classes usually involve both functionality (methods) & state (attributes on each instance).
Some classes are all about state, but they should never be all about methods.
A class of just methods should be a function. An oldie but goodie talk on this. π
pyvideo.org/pycon-us-2012/β¦
So calling a class makes an instance of that class. And classes typically have methods on them.
There are 3 methods I recommend implementing on every class.
The first is __init__ (the initializer).
I also recommend __repr__ & __eq__ to make your classes friendly to use.
There's *so* much more to say about classes in Python.
Here's a few places to start:
β‘οΈ pym.dev/what-is-a-clasβ¦
β‘οΈ pym.dev/classes-are-evβ¦
β‘οΈ pym.dev/what-is-self/?β¦
β‘οΈ pym.dev/what-is-init/?β¦
β‘οΈ pym.dev/inheriting-oneβ¦
And more here π
pym.dev/screencasts/clβ¦
Share this Scrolly Tale with your friends.
A Scrolly Tale is a new way to read Twitter threads with a more visually immersive experience.
Discover more beautiful Scrolly Tales like this.
