"__new__ VS __init__" In Python Tutorial (Simplified Explantion)

  Рет қаралды 27,779

Indently

Indently

Күн бұрын

In this video we're going to be looking at the difference between _new_ and _init_ in Python! We'll cover how they work and how we can use them.
▶ Become job-ready with Python:
www.indently.io
▶ Follow me on Instagram:
/ indentlyreels
00:00 Intro
00:20 Getting started
00:49 Private attribute
00:58 _new_
02:53 _init_
03:03 Running the example
04:27 Quick summary
05:02 Another example
08.28 Summing it up

Пікірлер: 40
@Darktega
@Darktega Жыл бұрын
I think it’s worth noting that in the singleton pattern example, “init” will *always* get called after “new” if an instance is returned in “new”, meaning that if constructor gets called twice and you are setting up some attributes in “init”, those will get overridden in the next call, but object instance will be still technically the same in the example of the video.
@vorpal22
@vorpal22 Жыл бұрын
Good video. I have almost never used __new__ and have done my singletons through metaclasses where a Singleton metaclass maintains a dict of instances, but this did actually teach me some things I wasn't entirely sure of about __new__.
@thodorisevangelakos
@thodorisevangelakos 11 ай бұрын
Been lovong your channel. Lots of neat insight!
@user-vi1tw1xw7r
@user-vi1tw1xw7r 7 ай бұрын
Concise and clear as always I'm finding. Thanks for some excellent explanations.
@berkaybakacak
@berkaybakacak Жыл бұрын
new day new information... This is the first time i see the __new__ keyword in Python. Thanks Indently, subscribed
@frd85
@frd85 Жыл бұрын
Very helpful.
@yashkulkarni2434
@yashkulkarni2434 11 ай бұрын
Can someone tell me how was Super() invoked even though Connection isn't extending any parent class?
@rishiraj2548
@rishiraj2548 Жыл бұрын
Thank you
@purplecrayon7281
@purplecrayon7281 11 ай бұрын
This is what I think is happening from the Vehicle example. If a vehicle has either 2 or 4 wheels, they become instances of the Vehicle class that has been initialized beforehand. But in a rare occurrence where a vehicle does NOT have 2 or 4 wheels, a new class is automatically created using __new__, but you will also need to initialize this new class with the necessary parameters/arguments. In a nutshell, you use __new__ as some kind of a "backup" class in case the instance does not meet the originalclass parameters.
@viktoreidrien7110
@viktoreidrien7110 Жыл бұрын
thanks bro
@luis_english-xy8gh
@luis_english-xy8gh 3 ай бұрын
Great video. Do you have any video explaining why ___ is used to initialize variables? I did it in C#, but I don't know if it's the same thing.
@Sinke_100
@Sinke_100 Жыл бұрын
I been thinking this dude lately does videos just to get something out with little to no value, yet this one is quite interesting new thing that I didn't know of, and might be helpfull in some occasions, I would definetly try it out...hope it's now a feature of python 3.11 cause I am using 9 and 10
@Indently
@Indently Жыл бұрын
I appreciate you subscribing to someone who posts videos with little or no value 😂
@Sinke_100
@Sinke_100 Жыл бұрын
@@Indently you love Python and you have nice voice, I guess good enough to stay subscribed 🙂 keep it up man, no hate here
@robertobokarev439
@robertobokarev439 10 ай бұрын
The thing I found out is that you can annotate stated types in __new__ and dynamicly annotate in __init__ with TypeVars for Generics as an example. Just to not mess up with code.
@NoProblem76
@NoProblem76 10 ай бұрын
Usually only used in library codes, avoid using __new__ at work. unless you have no other choice. Your IDE will get confused by this as it does not execute __new__ for u and it just assumes constructing an instance will return a new instance. Not to mention people that use your class would get so confused and could make mistake.
@davidm.bm01
@davidm.bm01 Ай бұрын
3:56 if the object doesn't have __eq__ the code performs de is operator
@mrhunter7
@mrhunter7 Жыл бұрын
which editor are you using ?
@woster4055
@woster4055 Жыл бұрын
It is pycharm with beta UI
@maxca
@maxca Жыл бұрын
So in the last example, when we create mb = Vehicle(2), mb is an object of the class Motorbike and no longer Vehicle?
@naturfagstoff
@naturfagstoff Жыл бұрын
No. It is both, mb is a Vehicle of 'type' Motorbike.
@ron与数学
@ron与数学 Жыл бұрын
@@naturfagstoff MaxCa is right. It is no longer a Vehicle. Please see my other comment for details.
@ron与数学
@ron与数学 Жыл бұрын
It's strange that my comment didn't show up. I will just copy it and rephrase it here. 1. The example here loses the point that the Motorcycle and Car should inherit from the Vehicle class. I know that Indently is trying to show the power of __new__() but I think it is worth pointing out that if someone wrote code this way, the code better be refactored. 2. A function/method should only do what its name says, nothing more. The __new__() method is responsible for creating the instance. However, by returning `Motorcycle()` directly. It implicitly called the Motorcycle's __init__() method. I refactored the code a little bit. class Vehicle: def __new__(cls, wheels): if wheels == 4: return super(Vehicle, cls).__new__(Car) elif wheels == 2: return super(Vehicle, cls).__new__(Motorcycle) else: pass def __init__(self, wheels): self.wheels = wheels class Car(Vehicle): def __new__(cls, *args, **kwargs): print("Creating Car") return super(Car, cls).__new__(cls) def __init__(self, wheels): print("Initializing Car with 4 wheels") super(Car, self).__init__(wheels) class Motorcycle(Vehicle): def __new__(cls, *args, **kwargs): print("Creating Motorcycle") return super(Motorcycle, cls).__new__(cls) def __init__(self, wheels): print("Initializing Motorcycle with 2 wheels") super(Motorcycle, self).__init__(wheels)
@Indently
@Indently Жыл бұрын
I completely forgot to inherit from Vehicle, you're right!
@naturfagstoff
@naturfagstoff Жыл бұрын
Apologize for my kneejerk reaction there, @maxca. You are completely right. @hollyandprosper explains it in detail. Even if the Vechilcle class is called upon, and thus should be creating an object of type Vehicle, it does not do that, but instead creates Motorbike if 2 vheels, and a Car if 4 vheels. Strangely enough, the Vechicle class only creates an instance of it's own type as an exception, that is if the number of wheels is NOT 2 or 4. And as @Indently admints, he completely forgot to inherit from Vehicle when defining those two other classes, Motorbike and Car. I was too quick there,and maybe made the same mistake as @Indently, in assuming the code followed usual design principles for classes and objects, but the code actually does not do that. So excellent and very important point.
@turboblitz4587
@turboblitz4587 Жыл бұрын
Unfortunately, this did not really explain to me what __ new__ actually does. It was more of a complicated Singleton Implementation
@rogumann838
@rogumann838 Жыл бұрын
That's what the video was, as he stated in the first 15 seconds
@mking1982098
@mking1982098 Жыл бұрын
new is performed before the instance of the object is created, whereas init runs after the object is already created. This means you can use the __new__ method to do things like set conditions and rules for the creation of an instance. e.g., you can do value error handling etc. before actually creating instance, whereas with init any error handling breaks etc. may stop certain attributes of the class from being set and whatnot but the instance will still be created.
@CoentraDZ
@CoentraDZ Жыл бұрын
And that's how you implement a Singleton using Python.
@arkie87
@arkie87 4 ай бұрын
how on earth do you get pycharm to look that good
@alexjando4880
@alexjando4880 Жыл бұрын
Great video, but it's pretty much a complete copy of mCoding. In his video he has the exact same connection example, and a similar example to vehicles.
@Indently
@Indently Жыл бұрын
If that's what you think, looks like mCoding copied it from the same website that I got the examples from 😂
@edhyjoxenbyl1409
@edhyjoxenbyl1409 Жыл бұрын
@@Indently The thing is mCoding writes it own examples
@Indently
@Indently Жыл бұрын
So do I, but I'm not hiding that I take inspiration from examples that are shown on python.org, or other websites. The original example for the vehicle was actually inspired by an example that was meant for an Animal class, where instead of wheels, they used legs.
@i007c
@i007c Жыл бұрын
what is this a mcoding clone 😂😂
@Indently
@Indently Жыл бұрын
Not at all, mCoding is an incredibly talented programmer and teacher. I make videos because I love Python :)
Is THIS Python's MOST Underrated Operator? (Walrus Operator)
5:45
5 Useful Dunder Methods In Python
16:10
Indently
Рет қаралды 54 М.
Who has won ?? 😀 #shortvideo #lizzyisaeva
00:24
Lizzy Isaeva
Рет қаралды 21 МЛН
The child was abused by the clown#Short #Officer Rabbit #angel
00:55
兔子警官
Рет қаралды 24 МЛН
PYTHON MAGIC METHODS. __INIT__ и __NEW__
14:53
luchanos
Рет қаралды 6 М.
20 Everyday Tips & Tricks in Python
25:18
Indently
Рет қаралды 16 М.
5 Good Python Habits
17:35
Indently
Рет қаралды 416 М.
__new__ vs __init__ in Python
10:50
mCoding
Рет қаралды 206 М.
10 Ways You Can Use "_" In Python (Do you know ALL of them?)
9:56
__new__ или __init__ в Python? Знаете ли вы это..
12:37
5 Tips To Write Better Python Functions
15:59
Indently
Рет қаралды 96 М.
PLEASE Use These 5 Python Decorators
20:12
Tech With Tim
Рет қаралды 101 М.
Metaclasses in Python
15:45
mCoding
Рет қаралды 150 М.
Python's Type Annotations DON'T Do What You THINK They Do
8:10