+ 15
(python)class without __init__ still works?
20 Respostas
+ 11
Simon Sauter Lea The problem here is the terminology. Many people call __init__ a constructor. But __init__ is not a constructor! It plays the role of a constructor, but is essentially just an initializer. It allows you to configure a ready-made object. A constructor returns a new object. A __init__ call, on the other hand, will simply change the properties of an existing object.
+ 5
Lea
Yes it will work without _init_ but when you want to create an instance of class then it is required.
Since you have static method so no need to create instance of class, you can directly call function through class name
+ 5
A͢J - S͟o͟l͟o͟H͟e͟l͟p͟e͟r͟ actually you can still create instances even if you don't explicitly define __init__(). I think in that case python implicitly uses the __init__() method of the (featureless) object class.
+ 3
In Python, the __init__() method plays the role of a constructor when creating an instance of a class.
In your case, the object is not created, you just call a static method of the class. You might as well just take it out of the class.
+ 3
__init__ is like a constructor
+ 2
A͢J - S͟o͟l͟o͟H͟e͟l͟p͟e͟r͟ Ok, so if i create a Rectangle, I won’t get its area with out __init__(), right?
+ 2
Alexey Kopyshev Haha yes, you are right, i’m learning staticmethod, that’s why, thank you for helping me!
+ 2
Simon Sauter It's true. Explicitly writing __init__ makes it possible to set default parameters and object behavior, but even without explicit __init__ will be called when the object is created
+ 2
Just add these lines to your code to see:
a = Shape()
print(a)
+ 2
The reason is that in Python 3 all classes inherit from the object class. (In Python 2 there are old-style classes which do not inherit from the object class and new-style classes which do.)
+ 2
You can read this for more information if you're interested:
https://stackoverflow.com/questions/4015417/why-do-JUMP_LINK__&&__python__&&__JUMP_LINK-classes-inherit-object
+ 2
Alexey Kopyshev Simon Sauter Thank you for all the info shared. Those really improve my understanding about __init__. Thank you for helping me!
+ 1
Alexey Kopyshev Excuse me, take what out of the class? The staticmethod?
+ 1
Lea I mean, if you only have one static method and nothing else, there's no point in creating a class.
+ 1
Simon Sauter What!? Really? Could you show me a simple example?
+ 1
__init__ is for create a variable of the class
- 4
What do you mean by html
- 4
In python command line how can we save the file
- 5
yeah that good I like the deatlis and if eneyone sees this check my codeing