MENU

Fun & Interesting

__new__ vs __init__ in Python

mCoding 212,964 4 years ago
Video Not Working? Fix It Now

What's __new__ and what's the difference vs. __init__? Try Hostinger: https://hostinger.com/mcoding Use coupon code MCODING at checkout for up to 91% off all yearly hosting plans! What's the difference between the "__new__" and "__init__" magic methods in Python? New is for object creation, and init is for object initialization. It is rare that a programmer would actually need to override new, so let's see some examples of how it can be used. ― mCoding with James Murphy (https://mcoding.io) Source code: https://github.com/mCodingLLC/VideosSampleCode Python new docs: https://docs.python.org/3/reference/datamodel.html#object.__new__ tp_new in CPython: https://github.com/python/cpython/blob/main/Objects/typeobject.c C extension example: https://cython.readthedocs.io/en/latest/src/userguide/extension_types.html#existing-pointers-instantiation Singleton pattern: https://en.wikipedia.org/wiki/Singleton_pattern SUPPORT ME ⭐ --------------------------------------------------- Patreon: https://patreon.com/mCoding Paypal: https://www.paypal.com/donate/?hosted_button_id=VJY5SLZ8BJHEE Other donations: https://mcoding.io/donate Top patrons and donors: Laura M, Jameson, John Martin, Dragos C, Vahnekie, Pieter G, Sigmanificient, Casey G BE ACTIVE IN MY COMMUNITY 😄 --------------------------------------------------- Discord: https://discord.gg/Ye9yJtZQuN Github: https://github.com/mCodingLLC/ Reddit: https://www.reddit.com/r/mCoding/ Facebook: https://www.facebook.com/james.mcoding CHAPTERS --------------------------------------------------- 0:00 Intro 0:50 New vs init 2:51 Main purpose, subclassing immutable types 5:03 Singleton example 6:35 Client caching example 7:58 Encrypted file example 10:33 Metaclasses

Comment