instantiate (verb): to make an "instance" of a class
Okay... but what's an "instance"? 🤔
instance (noun): an object
Wait, that's not a helpful definition.
Let's talk about class instances and class instantiation in Python.
#TerminologyTuesday
You can think of a "class" as a blueprint for making an objects that have specific functionality and contain particular types of data. 📘
list is a class in #Python
>>> list
<class 'list'>
An "instance of the list class" could also be called a "list object" or just "a list".
So instances of the list class (a.k.a. "lists") share their functionality with other list instances.
Here's 2 list instances:
>>> a = []
>>> b = []
They each have the same methods:
>>> a.append(2)
>>> b.append(5)
But they store separate data:
>>> a
[2]
>>> b
[5]
Every object in Python is an instance of some sort of class.
Dictionaries are instances of the dict class:
>>> d = {}
>>> type(d)
<class 'dict'>
Integers are instances of the int class:
>>> n = 3
>>> type(n)
<class 'int'>
This really applies to EVERY object in #Python 🤔
Functions are instances:
>>> def greet(name): print("Hi", name)
...
>>> type(greet)
<class 'function'>
Modules are instances:
>>> import math
>>> type(math)
<class 'module'>
And CLASSES are even instances:
>>> type(list)
<class 'type'>
Classes are "type" instances 😮
But what's "type" an instance of?
I bet you think you've found a gotcha. But the Python core devs thought of that too.
The "type" class is (naturally...) an instance of itself:
>>> type(type)
<class 'type'>
It's class instances all the way down. 🐢🐢🐢
So the word "instance" on its own doesn't mean much (since everything is an instance of something).
An "X instance" or "instance of X" IS meaningful though. That means "an object whose type is X". 💡
For example "p" is a "Point instance" here:
>>> type(p)
<class 'point.Point'>
The object-oriented programming world has SO much terminology it can make your head spin.
There's class, instance, instantiate, constructor, initializer, method, attribute, and more. 😵
But don't be scared away! These terms often sound fancier than they need to.
Curious about those other terms?
I defined method here 👇
I defined "initialize" and "initializer method" here 👇
And I defined "class", "attribute" and other terms in the @PythonMorsels terminology page.
Here's a link to the definition of "class instance", which links off to many related terms.
pym.dev/terms/#instance
@PythonMorsels Did you enjoy this #TerminologyTuesday thread? 📑
I do one of these every week and these terms are pretty much always about #Python. 🐍
Foll me at @treyhunner so you don't miss next week's thread 🌠
And retweet to help others learn about class instances 👇
In case you missed it, I also defined "class" recently as well 👇
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.
