What's an "object" in Python?

According to the Python glossary, an object is:

> Any data with state (attributes or value) and defined behavior (methods). Also the ultimate base class of any new-style class.

What does that really mean? (thread🧵)

#Python #TerminologyTuesday
Usually when we think of an "object" we think of class instance. For example these are all objects:

>>> numbers = [2, 1, 3, 4, 7] # a list object
>>> colors = {"red", "green", "blue", "yellow"} # a set object
>>> name = "Trey" # a string object
>>> n = 3 # an int object
Anything that can have attributes is an object.

Anything that can has methods is an object.

Anything that you can point a variable to is an object.

Pretty much EVERY THING is an object in Python.
For example functions are objects in Python (we discussed this when discussing "callables")..

That means we can pass functions around to other functions. 😮

pym.dev/passing-functi…

That's how decorators work in Python.
But modules and classes are objects too!

Modules can have attributes:

>>> import math
>>> math.pi
3.141592653589793

And so can classes:

>>> class SomeClass:
... x = 4
...
>>> SomeClass.x
4

And as we noted when discussing "instances", both have a "type" also.
In Python, variables point to (a.k.a. "reference") objects.

So variables are NOT objects.

Variables and attributes are names that *refer* to objects.

But everything you can point a variable to IS an object.
Everything is an object, but not all objects are alike.

Some objects have attributes (e.g. __doc__) that other objects don't.

Some objects have behaviors (e.g. certain methods or index/key lookups) that other objects don't.

Some objects are mutable and some are immutable.
In Python:
• Anything you can point a variable to is an object
• Every function, module, class, & class instance is an object
• Some objects are mutable & some aren't (more another time)
• Different objects support different behaviors

A definition 👇

pym.dev/terms/#object

• • •

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

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
Aug 1
Need to remove all spaces from a string in #Python? 🌌🐍

Let's take a quick look at:

• removing just space characters
• removing all whitespace
• collapsing consecutive whitespace to 1 space
• removing from the beginning/end
• removing from the ends of every line

Thread🧵
If you just need to remove space characters you could use the string replace method to replace all spaces by an empty string:

>>> greeting = " Hello world! "
>>> greeting.replace(" ", "")
'Helloworld!'

But you may also want to remove other whitespace too (e.g. newlines)...
To remove all sorts of whitespace, you could use the string split method along with the string join method:

>>> version = "\tpy 310\n"
>>> "".join(version.split())
'py310'

Or you could use a regular expression:

>>> import re
>>> re.sub(r"\s+", "", version)
'py310'
Read 8 tweets
Jul 11
"Why does Python have a datetime.timedelta object?"

My Intro to #Python students sometimes ask me that question ☝

My answer:

1. Moments in time are not the same as durations of time
2. Sometimes an idea is important enough to warrant a new data type

Let me explain 🧵
First, let's note that datetime != timedelta

These represent moments in time:

>>> nye = datetime(2022, 12, 31)
>>> halloween = datetime(2022, 10, 31)

But this is a *duration* of time:

>>> nye - halloween
datetime.timedelta(days=61)

A datetime can't represent "61 days"
We need some way to represent a duration of time.

Why didn't the core devs use a float representing seconds?

Imagine datetime arithmetic that way 😖

>>> from datetime import timedelta
>>> nye - halloween
5270400.0
>>> halloween + 2*24*60*60
datetime.datetime(2022, 11, 2, 0, 0)
Read 6 tweets
Jun 1
Need to split up seconds into hours, minutes, & seconds in #Python?

This is one of the rare instances in which I might reach for Python's built-in divmod function. Though datetime.timedelta might work too, depending on your use case.

Let's compare int, //, divmod, & timedelta🧵
Given a number of seconds:

>>> duration = 4542

You might have thought to use division, modulo, and Python's int function 🤔

hours = int(duration/60 / 60)
minutes = int(duration/60 % 60)
seconds = duration % 60
But that int function is there because we're doing truncating division. Python has an operator just for that!

The // operator:

hours = duration // (60*60)
minutes = duration // 60 % 60
seconds = duration % 60

When x and y are ints, x//y is exactly the same as int(x/y).
Read 9 tweets
May 31
Another fundamental Python term for #TerminologyTuesday

callable: an object which can be called

The classical "callable" is a function, but in #Python classes are also callables.
In many programming languages (e.g. JS, PHP, C++) creating a new "instance" of a class (an object whose type is that class) involves the "new" keyword:

let eol = new Date(2020, 1, 1);

But in #Python to make a new class instance we just call the class:

eol = date(2020, 1, 1)
The fact that classes are callables means the distinction between a function and a class is often quite subtle. All of these "functions" are actually implemented as classes:

n = float("4.5")
m = int(n)
s = str(m)
b = bool(m)
t = tuple('abcd')
e = enumerate(t)
r = reversed(t)
Read 11 tweets
May 31
Python Quiz: what input will result in different behavior from the built-in int function and the math.floor function?

>>> int(x)
vs

>>> import math
>>> math.floor(x)

They're *usually* the same
Those replying negative numbers: you're absolutely right!

There's another input that has different behavior for math.floor and int in Python too. 🤔

Other guesses?
The two answers I've found are negative numbers and strings.

x = -3.3 # int returns -3 and floor returns -4

x = "3.3" # int returns 3 and floor raises TypeError

pym.dev/p/2tc43/
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 on Twitter!

:(