12 Antworten
+ 1
__init__ is a special Python method that is automatically called when memory is allocated for a new object. The sole purpose of __init__ is to initialize the values of instance members for the new object.
It'll also helps in speeding up the process... If we don't provide it, it'll search for the constructor in the parent class(i.e., object class)
0
class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to it for maintaining its state. Class instances can also have methods (defined by its class) for modifying its state.
Coming to __init__ , it is constructor....
https://docs.python.org/3/tutorial/classes.html
Hope it will be helpful...
0
please explain me what __init__ is used?? i mean what's its necessity??
0
Constructors are used to initialize the object's state. The task of constructors is to initialize(assign values) to the data members of the class when an object of class is created.
OR
__init__ is a special Python method that is automatically called when memory is allocated for a new object. The sole purpose of __init__ is to initialize the values of instance members for the new object.
0
Class is a model of something or blueprint with properties and behaviors.
__init__ is a constructor which automatically runs when instance is created.
When learning object oriented programming... Learn to make class, class varaible..class method, static method, constructor, method, decorator, inheriting class, etc...
0
please give me some examples !! still im unable to get!! i respect your efforts though!!😣
0
class Employee:
def __init__(self, name, age) :
self.name=name
self.age=age
def func(self) :
print("Welcome")
emp1=Employee("Ram",25)
emp1.func()
print(emp1.name)
print(emp1.age)
Here, emp1=Employee("Ram",25)
indicates that you are creating an object to that class... As I already said __init__ is constructor... It automatically gets called whenever object is created... So, all the the arguments (Ram and 25) are passed to that constructor.... And the the next lines hope you know all those... So, the o/p is
Welcome
Ram
25
0
i got it!! thank you!! but what if we define name and age inside the func method?? and remove the init!!🤔
0
it may be helpful!
https://www.sololearn.com/discuss/2296137/?ref=app
0
No problem... It works well... But, you have to pass the parameters in func()
0
so whats the necessity of init then??
0
Lucky,
if you use constructor, you dont need to create such lengthy functions, you can directly pass values that a class need!