type(obj) vs. obj.__class__ in Python, and changing an object's class.

preview_player
Показать описание
What's the difference?

Python has two way to access the type of an object. There's type(obj) and obj.__class__. What's the difference? In this video we see how they are mostly the same (and you probably shouldn't worry about it) but there is a difference in that it's possible for a class to lie about what type it is by intercepting accesses to __class__. The builtin type on the other hand will always give you the real type of the object. Although, if a class tries to lie about it's type, maybe it has a good reason for it, which means you might prefer using __class__ for this reason. It's also possible to modify an objects __class__ at runtime after the object has been created, which will truly change the type so that type(obj) and obj.__class__ both report the new type. There are some restrictions (and use cases are questionable!) but it's good to know in case you ever feel like something funny is going on.

SUPPORT ME ⭐
---------------------------------------------------
Sign up on Patreon to get your donor role and early access to videos!

Feeling generous but don't have a Patreon? Donate via PayPal! (No sign up needed.)

Want to donate crypto? Check out the rest of my supported donations on my website!

Top patrons and donors: Jameson, Laura M, Dragos C, Vahnekie, Neel R, Matt R, Johan A, Casey G, Mark M, Mutual Information, Pi

BE ACTIVE IN MY COMMUNITY 😄
---------------------------------------------------

CHAPTERS
---------------------------------------------------
0:00 Intro
0:34 How to use type(obj)
1:43 What about obj.__class__?
3:08 Lie about your __class__
3:56 Changing __class__ at runtime
6:44 Example: custom module type
7:36 Example: Reading pre-initialized object
9:34 Thanks
Рекомендации по теме
Комментарии
Автор

I tend to use #class for user defined classes or more abstract classes, and #type for base types, like ints or strs.

AntonioZL
Автор

I used to be a #class person before your video, but now I'm totally #type.
Thanks as always for deep dives and interesting facts about Python. Love your vids, keep it up!

Phaust
Автор

#type
Directly accessing dunder attributes/methods almost always looks janky

danwellington
Автор

so when are we getting reinterpret_cast for python objects

jemand
Автор

#class, and I actually use the runtime class change in one of my projects. Yes, it has an actual use in my case.
But where I do it, the classes basically don't have any extra initialization to be done, so... Bad code quality, but it's the only way it works.
At least it works.

EDIT:
My bad, I'm modifying instance.___bases___ rather than instance.___class___ ! Sorry for the confusion !

mathieuflouret
Автор

5:16 i nearly spat out my tea, thanks James

MilChamp
Автор

I'm feeling like #class is more convenient while working with a class and #type is more convenient while working with plain types (e.g. int, str, float, bytes)

SyberiaK
Автор

5:16 that was incredible, so out of left field, I love it.




#type

adamdapatsfan
Автор

#class thanks for the demonstration, that's good to know

Scymet
Автор

Dude! You are carrying us to dark side of python, keep it on! I really love you channel. Yours and the one from ArjanCodes just have fantastic content.

julianbazanaguirre
Автор

Thanks for the (as usual) precious insight! I wonder, is the behaviour of "isinstance" affected by this ?

paper_cut
Автор

8:35 this is actually cool and useful!

Cyber_Chriis
Автор

#3:40 you don't do that because you have great job security, but as a way of getting it! If nobody else can maintain your code, they can't get rid of you

QuantumHistorian
Автор

I use #type for runtime type checking, i.e. type(obj1) == type(obj2). I use #class for introspection-like scenarios, especially if I'm viewing the classname. like I would never write: if obj.__class__ == int nor would I write print(type(self).__name__)

marckiezeender
Автор

#class I never knew you could use type(self) in place of self.__class__, so it looks funny :|

RichardFeynman
Автор

Im working on an admin panel builder for flask. Definitely been pushing all these techniques to the extreme.

thagreatone
Автор

"If you do this you must have incredible job security" lol I come here for the jokes!

fartzy
Автор

#type If a builtin function is avaiilable, as a matter of style, I always prefer it over a dunder attribute/method. Like, no one would write `list.__setitem__(index, value)` instead of `list[index] = value`, so why treat `__class__` differently?

felixfourcolor
Автор

my god, I was just thinking about this topic this morning in my bed and now I get a new video from you on this topic.. #Google_reading_minds

elrandira
Автор

Just found your channel and subbed. This is the second video I see from you, the other was 25 nooby habits. Just letting you know: while this is still perfectly audible, your older video had way better audio, and I can see this 'dull' sound leading to fatigue.

TobyLegion