Trey Hunner (Python trainer) Profile picture
Sep 6 โ€ข 7 tweets โ€ข 4 min read
Python class curious? ๐Ÿค”

Here's a 4-in-1 thread about class-related Python terms ๐Ÿ

โ€ข class
โ€ข class instance
โ€ข method
โ€ข initializer method

Make sure to click through to each of the 4 thread for more ๐Ÿงต

#Python #TerminologyTuesday
A class is essentially a template for creating an object in Python.

Every object has a class, seen by the "type" function:

>>> type(4)
<class 'int'>

The terms "type" & "class" are synonyms in Python.

Some "functions" are actually implemented as classes.

On ๐—ฐ๐—น๐—ฎ๐˜€๐˜€๐—ฒ๐˜€ ๐Ÿ–ฑ๏ธ
Calling a class returns an "instance" of that class.

All objects are instances of their "type".

>>> x = True
>>> type(x) == bool
True
>>> isinstance(x, bool)
True

But objects are instances of parent classes as well:

>>> isinstance(x, int)
True

On ๐—ถ๐—ป๐˜€๐˜๐—ฎ๐—ป๐—ฐ๐—ฒ๐˜€ ๐Ÿ–ฑ๏ธ
Methods are functions attached to classes. They're typically designed to operate on instances of the class.

Under the hood every method call:

>>> numbers.append(3)

Is translated to a function call on the class itself:

>>> type(numbers).append(numbers, 3)

On ๐—บ๐—ฒ๐˜๐—ต๐—ผ๐—ฑ๐˜€ ๐Ÿ–ฑ๏ธ
When defining a class, the first method you'll define is often __init__, the initializer method.

Want to accept arguments when calling your class?

Want to initialize attributes on your class instance?

That's what __init__ is for.

On ๐—ถ๐—ป๐—ถ๐˜๐—ถ๐—ฎ๐—น๐—ถ๐˜‡๐—ฒ๐—ฟ๐˜€ ๐Ÿ–ฑ๏ธ
I'm taking a #TerminologyTuesday break during September. ๐Ÿต

I'll be re-sharing past terminology Tuesday threads each week for the next 4 weeks. ๐Ÿ”„

This was the first Python terminology revisit. ๐Ÿ

Stay tuned for #Python terminology reruns over the next 4 weeks. ๐ŸŒ 
Learn something new? ๐Ÿ๐Ÿ’–

For more terminology Tuesday tweets and daily #Python tips, follow me at @treyhunner and @PythonMorsels. ๐ŸŒ 

For my longer-form Python tips, get on my email newsletter: pym.dev/newsletter ๐Ÿ“จ

โ€ข โ€ข โ€ข

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

Keep Current with Trey Hunner (Python trainer)

Trey Hunner (Python trainer) 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

Sep 7
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
Aug 30
What's "assignment" in #Python?

This might seem like a simple concept, but there are some gotchas in the way assignment works in Python.

Fundamentally "assignment" describes the action of binding a name to a value.
You can assign a variable (a.k.a. name) to a value (a.k.a. object) with an "assignment statement".

That uses an = sign, like this:

>>> x = []

That assigns the name x to an empty list.

If "x" already exists, an = sign will re-assign it to a new value:

.>>> x = 4
>>> x
4
Python programmers often talk about names "binding" to objects or variables "pointing" to objects.

In Python, variables point to (or "refer to") values. Variables don't *contain* objects, but just say "look over there for the object". ๐Ÿ‘€

Beware of code like this:

x = []
y = x
Read 14 tweets
Aug 29
Python's strings have 47 methods!

But these 12 string methods are the only ones really worth committing to memory for most Python programmers:

join
split
replace
strip
casefold
startswith
endswith
splitlines
format
count
removeprefix
removesuffix A table showing the 12 stri...
But what about find, encode, translate, isnumeric, and all the other string methods?

While there are other useful string methods, most of the remaining methods have a niche use case or have quirks that make them tricky to use.

For example the title method has quirks ๐Ÿ‘‡
And methods like isnumeric, isdigit, and isdecimal unfortunately take a bit of studying to figure out, so I recommend either avoiding them or using them carefully.
Read 5 tweets
Aug 23
What's a "generator" in Python?

#TerminologyTuesday time โฐ

Let's discuss:
โ€ข The main reason generators are used
โ€ข The 2 ways to make a generator
โ€ข Lesser known generator features
โ€ข Why and when to use generators

Thread ๐Ÿงต๐Ÿ‘‡
Generators are typically used as lazy iterables.

By "lazy" I mean that they don't actually compute their values until they absolutely need to.

Essentially generators will "generate" their next value as soon as they're asked for it.
Here's a generator of every .py file in my home directory:

>>> from pathlib import Path
>>> py_files = Path.home().rglob("*.py")
>>> py_files
<generator object Path.rglob at 0x7f5a6721c900>

(the rglob method on pathlib.Path objects always returns a generator)
Read 21 tweets
Aug 9
What's a regular expression (a.k.a. regex)? ๐Ÿค” #TerminologyTuesday

Yes, they're a programming language within a programming language that's just for pattern matching and they're extremely succinct.

But what does "regular expression" really mean? And where did they come from?
Haven't seen regular expressions?

Imagine a special purpose programming language where every single character is a statement and no whitespace or comments are allowed. ๐Ÿ˜จ

Regular expressions are extremely information dense but very helpful for certain types of pattern matching.
Regular expressions are called "regular" because regular expressions define a "regular language".

What's a "regular language"?

I'm so glad you asked! This is one of the few factoids from my CS degree that actually stuck with me.

This part of CS is tightly tied to linguistics.
Read 17 tweets
Aug 3
I usually recommend the "literal" list & dict syntax in #Python over the built-in list & dict functions.

โœ… []
๐Ÿšซ list()

โœ… {}
๐Ÿšซ dict()

โœ… {"name": "Trey", "id": 4}
๐Ÿšซ dict(name='Trey', id=4)

So what's the purpose of list(...) and dict(...)? ๐Ÿค”

Copying!

(thread๐Ÿงต)
Per the Zen of Python:

> there should be oneโ€” and preferably only one โ€”obvious way to do it

I see [] and {} as "the one obvious" way to make a new list/dict.

[] and {} are even more common than list() and dict() so are likely more obvious to most Python devs.
What about passing keyword arguments to dict(...)?

This is a neat trick, but its use is limited.

Using non-string or invalid Python variables as keys doesn't work:

>>> d = dict(class="yes")
SyntaxError: invalid syntax

I don't find the benefits of dict(...) worth 2 syntaxes.
Read 8 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 on Twitter!

:(