Course Intro & Example Python Class
This lesson will show you why you would want to control how a Python class is represented. In the lesson, you’ll create a Python class and see what happens when you try to print out one of its instances to the console. The result of doing this is relatively unsatisfying.
00:00 Today, I want to talk about how you can control how a Python class is represented as a string, and also when you interact with it or inspect it in a Python interpreter session.
00:12
So, let’s start with a really simple example here. I’ve got my popular Car
class, and we’re just going to create a simple Car
object here.
00:24
And what you can see is that when I print this Car
object, we kind of get this unsatisfying result, and it’s the same when I just inspect the object in this interpreter session. So you can see here, well, at least it gives us the class name—kind of the whole namespace of this thing—but it only gives us the memory address if we’re on CPython, you know, it just gives us this ID. And it’s kind of opaque and kind of hard to understand what’s going on. So, this is better than nothing, but it’s not super useful.
Bartosz Zaczyński RP Team on Aug. 3, 2020
It’s a quirk of bpython, which is an alternative Python interpreter that Dan’s using. In addition to this, he must have had executed a module called “console.py” in an interactive mode:
$ bpython -i console.py
The default string representation of a user-defined class is prefixed with the name of a module it was defined in.
Become a Member to join the conversation.
Cedric Liu on July 30, 2020
Why is the return value here shows console instead of main?