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

Описание к видео type(obj) vs. obj.__class__ in Python, and changing an object's class.

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.

― mCoding with James Murphy (https://mcoding.io)

Source code: https://github.com/mCodingLLC/VideosS...
https://docs.python.org/3/reference/d...

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

Feeling generous but don't have a Patreon? Donate via PayPal! (No sign up needed.)
https://www.paypal.com/donate/?hosted...

Want to donate crypto? Check out the rest of my supported donations on my website!
https://mcoding.io/donate

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 😄
---------------------------------------------------
Discord:   / discord  
Github: https://github.com/mCodingLLC/
Reddit:   / mcoding  
Facebook:   / james.mcoding  

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

Комментарии

Информация по комментариям в разработке