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
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
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:
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 🤔
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)