Trey Hunner Profile picture
Jul 12, 2022 โ€ข 13 tweets โ€ข 5 min read โ€ข Read on X
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 ๐Ÿ‘‡

โ€ข โ€ข โ€ข

Missing some Tweet in this thread? You can try to force a refresh
ใ€€

Keep Current with Trey Hunner

Trey Hunner Profile picture

Stay in touch and get notified when new unrolls are available from this author!

Read all threads

This Thread may be Removed Anytime!

PDF

Twitter may remove this content at anytime! Save it as PDF for later use!

Try unrolling a thread yourself!

how to unroll video
  1. Follow @ThreadReaderApp to mention us!

  2. From a Twitter thread mention us with a keyword "unroll"
@threadreaderapp unroll

Practice here first or read more on our help page!

More from @treyhunner

Mar 14, 2023
Instead of getter and setter methods, in #Python we often use a property to control what happens when we get/set a specific attribute.

>>> r = Rectangle(5, 4)

With a property, instead of this:

>>> r.get_area()
20
>>> r.set_area(8)

We can do this:

>>> r.area
20
>>> r.area = 8 Image
You can think of a property as a virtual attribute.

Accessing a property runs a function. And so does assigning to a property!

Don't believe me? Try running this and take a look at what's printed.

pym.dev/p/2krm5/
By default a property can be read from but not written to.

class Circle:
def __init__(self, r):
self.r = r
@โ€property
def d(self):
return self.r*2

>>> c = Circle(2)
>>> c.d
4
>>> r.d = 5
AttributeError: property 'd' of 'Circle' object has no setter
Read 4 tweets
Mar 10, 2023
In Python we don't have "main" functions.

Instead we ask the question "is my module the entry point to this #Python process?"

We do that with this very strange looking condition:

if __name__ == "__main__":
main()
Why does this work? ๐Ÿค”

Well, each module has a __name__ variable in it which represents the name of that module. There's also __file__, which is its file path and __doc__ which is its docstring.

But when Python runs a module as a script, it does something different...
Every #Python process has one module which acts as its entry point.

When you run "python3 my_script.py", you're telling Python to use the my_script.py file as the entry point module.

The entry point module doesn't get its own name, but a special one instead: "__main__".
Read 6 tweets
Mar 9, 2023
There are 3 methods I implement on most #Python classes I make.

โ€ข __init__: the initializer method
โ€ข __repr__: the programmer-readable string representation
โ€ข __eq__: implement a nice sense of equality (what the == operator does)

__init__ & __repr__ always, __eq__ usually
If you're inheriting from another class you'll likely get some (or all) of those for free.

But if you're creating your own class, it's easy to overlook __repr__ and even easier to overlook __eq__.

But both of those methods can make it easier to work with your class instances.
The tricky one of those 3 methods is __eq__.

Not all classes really have a sensible notion of equality outside of the "equality is identity" behavior that Python provides out of the box.

And implementing __eq__ makes objects unhashable by default, though that's rarely an issue.
Read 5 tweets
Mar 8, 2023
Need to de-duplicate items in a list?

>>> my_items = ["duck", "mouse", "duck", "computer"]

This works if you don't care about the order:

>>> unique_items = set(my_items)

If maintaining item order is important, this works:

>>> unique_items = list(dict.fromkeys(my_items))
Confused by list(dict.fromkeys(...))?

dict.fromkeys() accepts an iterable and creates a new dictionary with the iterable items as keys and None as the values.

list() accepts an iterable and creates a new list from its items

When you loop over a dictionary you get just the keys
That dict technique works because dictionaries have unique keys and dictionaries maintain the insertion order of their items.

Note that those two techniques only work for numbers, strings, or other hashable objects.
Read 4 tweets
Oct 3, 2022
Need the largest item in an iterable in #Python? ๐ŸŽš๏ธ

>>> max(iterable)

Need the largest n items in an iterable? โฌ†๏ธ

>>> from heapq import nlargest
>>> nlargest(n, iterable)

Need all items arranged from largest to smallest? ๐Ÿ“‰

>>> sorted(iterable, reverse=True)
Need the smallest item in a #Python iterable? โš–๏ธ

>>> min(iterable)

Need the n smallest items? โฌ‡๏ธ

>>> from heapq import nsmallest
>>> smallest(n, iterable)

If you need all of them in increasing order, use sorted (no reverse) ๐Ÿ“ˆ

>>> sorted(iterable)
Here's a sort of cheat sheet for getting the smallest & largest items in #Python ๐Ÿ—’๏ธ๐Ÿ

Click the big green button to run the code ๐ŸŸข

Feel free to bookmark it for the next time you need this ๐Ÿ”–

pym.dev/p/39jsj/
Read 5 tweets
Sep 7, 2022
Python's "for" loops can only loop in one direction: forwards!

If you need to loop in the reverse direction, the built-in "reversed" function can help.

>>> colors = ["pink", "blue", "green"]
>>> for color in reversed(colors):
... print(color)
...
green
blue
pink
The "reversed" function only works on reversible iterables.

Fortunately, most of the iterables you might care to reverse *are* reversible.

Sequences (e.g. lists, tuples, and strings) are reversible and so are dictionaries (as of Python 3.8).
Python's "for" loops are single-purposed: they can loop over an iterable 1 item at a time.

That's why these built-in looping helpers (and others) are such a big deal:

โ€ข reversed: loop in reverse
โ€ข enumerate: count upward while looping
โ€ข zip: loop over 2+ iterables at once
Read 4 tweets

Did Thread Reader help you today?

Support us! We are indie developers!


This site is made by just two indie developers on a laptop doing marketing, support and development! Read more about the story.

Become a Premium Member ($3/month or $30/year) and get exclusive features!

Become Premium

Don't want to be a Premium member but still want to support us?

Make a small donation by buying us coffee ($5) or help with server cost ($10)

Donate via Paypal

Or Donate anonymously using crypto!

Ethereum

0xfe58350B80634f60Fa6Dc149a72b4DFbc17D341E copy

Bitcoin

3ATGMxNzCUFzxpMCHL5sWSt4DVtS8UqXpi copy

Thank you for your support!

Follow Us!

:(