Why do we need __init__ to initialize a python class










4















I'm pretty new to OOP and I need some help understanding the need for a constructor in a python class.



I understand init is used to initialize class variables like below:



class myClass():
def __init__ (self):
self.x = 3
print("object created")

A = myClass()
print(A.x)
A.x = 6
print(A.x)


Output:



object created
3
6


but, I could also just do,



class myClass():
x = 3
print("object created")

A = myClass()
print(A.x)
A.x = 6
print(A.x)


which prints out the same result.



Could you please explain why we need a constructor or give me an example of a case when the above method will not work?










share|improve this question






















  • You can read about class members vs instance members in python. This should improve your understandings.

    – florin
    Nov 15 '18 at 11:33











  • You can pass arguments to the class object and assign those values to class members in the constructor.

    – Nitin Pawar
    Nov 15 '18 at 11:34






  • 2





    Why do we use __init__ in Python classes?

    – Johnny Mopp
    Nov 15 '18 at 11:36















4















I'm pretty new to OOP and I need some help understanding the need for a constructor in a python class.



I understand init is used to initialize class variables like below:



class myClass():
def __init__ (self):
self.x = 3
print("object created")

A = myClass()
print(A.x)
A.x = 6
print(A.x)


Output:



object created
3
6


but, I could also just do,



class myClass():
x = 3
print("object created")

A = myClass()
print(A.x)
A.x = 6
print(A.x)


which prints out the same result.



Could you please explain why we need a constructor or give me an example of a case when the above method will not work?










share|improve this question






















  • You can read about class members vs instance members in python. This should improve your understandings.

    – florin
    Nov 15 '18 at 11:33











  • You can pass arguments to the class object and assign those values to class members in the constructor.

    – Nitin Pawar
    Nov 15 '18 at 11:34






  • 2





    Why do we use __init__ in Python classes?

    – Johnny Mopp
    Nov 15 '18 at 11:36













4












4








4








I'm pretty new to OOP and I need some help understanding the need for a constructor in a python class.



I understand init is used to initialize class variables like below:



class myClass():
def __init__ (self):
self.x = 3
print("object created")

A = myClass()
print(A.x)
A.x = 6
print(A.x)


Output:



object created
3
6


but, I could also just do,



class myClass():
x = 3
print("object created")

A = myClass()
print(A.x)
A.x = 6
print(A.x)


which prints out the same result.



Could you please explain why we need a constructor or give me an example of a case when the above method will not work?










share|improve this question














I'm pretty new to OOP and I need some help understanding the need for a constructor in a python class.



I understand init is used to initialize class variables like below:



class myClass():
def __init__ (self):
self.x = 3
print("object created")

A = myClass()
print(A.x)
A.x = 6
print(A.x)


Output:



object created
3
6


but, I could also just do,



class myClass():
x = 3
print("object created")

A = myClass()
print(A.x)
A.x = 6
print(A.x)


which prints out the same result.



Could you please explain why we need a constructor or give me an example of a case when the above method will not work?







python constructor init






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 15 '18 at 11:29









DiletanteDiletante

10418




10418












  • You can read about class members vs instance members in python. This should improve your understandings.

    – florin
    Nov 15 '18 at 11:33











  • You can pass arguments to the class object and assign those values to class members in the constructor.

    – Nitin Pawar
    Nov 15 '18 at 11:34






  • 2





    Why do we use __init__ in Python classes?

    – Johnny Mopp
    Nov 15 '18 at 11:36

















  • You can read about class members vs instance members in python. This should improve your understandings.

    – florin
    Nov 15 '18 at 11:33











  • You can pass arguments to the class object and assign those values to class members in the constructor.

    – Nitin Pawar
    Nov 15 '18 at 11:34






  • 2





    Why do we use __init__ in Python classes?

    – Johnny Mopp
    Nov 15 '18 at 11:36
















You can read about class members vs instance members in python. This should improve your understandings.

– florin
Nov 15 '18 at 11:33





You can read about class members vs instance members in python. This should improve your understandings.

– florin
Nov 15 '18 at 11:33













You can pass arguments to the class object and assign those values to class members in the constructor.

– Nitin Pawar
Nov 15 '18 at 11:34





You can pass arguments to the class object and assign those values to class members in the constructor.

– Nitin Pawar
Nov 15 '18 at 11:34




2




2





Why do we use __init__ in Python classes?

– Johnny Mopp
Nov 15 '18 at 11:36





Why do we use __init__ in Python classes?

– Johnny Mopp
Nov 15 '18 at 11:36












2 Answers
2






active

oldest

votes


















4














Citation: But I can also do



class myClass():
x = 3
print("object created")

A = myClass()
print(A.x)
A.x = 6
print(A.x)


No you cannot. There is a fundamental difference once you want to create two or more objects of this same class. Maybe this behaviour becomes clearer like this



class MyClass:
x = 3
print("Created!")

a = MyClass() # Will output "Created!"
a = MyClass() # Will output nothing since the class already exists!


In principal you need __init__ in order to write that code that needs to get executed for every new object whenever this object gets initialized / created - not just once when the class is read in.






share|improve this answer


















  • 1





    Thank you, this helped my understanding!

    – Diletante
    Nov 15 '18 at 11:44


















2














__init__ is used to initialize the state of multiple instances of a class where each instance's state is decoupled from each other, whereas your second example, without __init__ initializes an attribute that is shared among all instances of a class.






share|improve this answer























  • Okay, my understanding became clearer.. Thank you :)

    – Diletante
    Nov 15 '18 at 11:45










Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53318475%2fwhy-do-we-need-init-to-initialize-a-python-class%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









4














Citation: But I can also do



class myClass():
x = 3
print("object created")

A = myClass()
print(A.x)
A.x = 6
print(A.x)


No you cannot. There is a fundamental difference once you want to create two or more objects of this same class. Maybe this behaviour becomes clearer like this



class MyClass:
x = 3
print("Created!")

a = MyClass() # Will output "Created!"
a = MyClass() # Will output nothing since the class already exists!


In principal you need __init__ in order to write that code that needs to get executed for every new object whenever this object gets initialized / created - not just once when the class is read in.






share|improve this answer


















  • 1





    Thank you, this helped my understanding!

    – Diletante
    Nov 15 '18 at 11:44















4














Citation: But I can also do



class myClass():
x = 3
print("object created")

A = myClass()
print(A.x)
A.x = 6
print(A.x)


No you cannot. There is a fundamental difference once you want to create two or more objects of this same class. Maybe this behaviour becomes clearer like this



class MyClass:
x = 3
print("Created!")

a = MyClass() # Will output "Created!"
a = MyClass() # Will output nothing since the class already exists!


In principal you need __init__ in order to write that code that needs to get executed for every new object whenever this object gets initialized / created - not just once when the class is read in.






share|improve this answer


















  • 1





    Thank you, this helped my understanding!

    – Diletante
    Nov 15 '18 at 11:44













4












4








4







Citation: But I can also do



class myClass():
x = 3
print("object created")

A = myClass()
print(A.x)
A.x = 6
print(A.x)


No you cannot. There is a fundamental difference once you want to create two or more objects of this same class. Maybe this behaviour becomes clearer like this



class MyClass:
x = 3
print("Created!")

a = MyClass() # Will output "Created!"
a = MyClass() # Will output nothing since the class already exists!


In principal you need __init__ in order to write that code that needs to get executed for every new object whenever this object gets initialized / created - not just once when the class is read in.






share|improve this answer













Citation: But I can also do



class myClass():
x = 3
print("object created")

A = myClass()
print(A.x)
A.x = 6
print(A.x)


No you cannot. There is a fundamental difference once you want to create two or more objects of this same class. Maybe this behaviour becomes clearer like this



class MyClass:
x = 3
print("Created!")

a = MyClass() # Will output "Created!"
a = MyClass() # Will output nothing since the class already exists!


In principal you need __init__ in order to write that code that needs to get executed for every new object whenever this object gets initialized / created - not just once when the class is read in.







share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 15 '18 at 11:39









quantquant

1,60211527




1,60211527







  • 1





    Thank you, this helped my understanding!

    – Diletante
    Nov 15 '18 at 11:44












  • 1





    Thank you, this helped my understanding!

    – Diletante
    Nov 15 '18 at 11:44







1




1





Thank you, this helped my understanding!

– Diletante
Nov 15 '18 at 11:44





Thank you, this helped my understanding!

– Diletante
Nov 15 '18 at 11:44













2














__init__ is used to initialize the state of multiple instances of a class where each instance's state is decoupled from each other, whereas your second example, without __init__ initializes an attribute that is shared among all instances of a class.






share|improve this answer























  • Okay, my understanding became clearer.. Thank you :)

    – Diletante
    Nov 15 '18 at 11:45















2














__init__ is used to initialize the state of multiple instances of a class where each instance's state is decoupled from each other, whereas your second example, without __init__ initializes an attribute that is shared among all instances of a class.






share|improve this answer























  • Okay, my understanding became clearer.. Thank you :)

    – Diletante
    Nov 15 '18 at 11:45













2












2








2







__init__ is used to initialize the state of multiple instances of a class where each instance's state is decoupled from each other, whereas your second example, without __init__ initializes an attribute that is shared among all instances of a class.






share|improve this answer













__init__ is used to initialize the state of multiple instances of a class where each instance's state is decoupled from each other, whereas your second example, without __init__ initializes an attribute that is shared among all instances of a class.







share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 15 '18 at 11:42









solstice333solstice333

1,2331215




1,2331215












  • Okay, my understanding became clearer.. Thank you :)

    – Diletante
    Nov 15 '18 at 11:45

















  • Okay, my understanding became clearer.. Thank you :)

    – Diletante
    Nov 15 '18 at 11:45
















Okay, my understanding became clearer.. Thank you :)

– Diletante
Nov 15 '18 at 11:45





Okay, my understanding became clearer.. Thank you :)

– Diletante
Nov 15 '18 at 11:45

















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53318475%2fwhy-do-we-need-init-to-initialize-a-python-class%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Top Tejano songwriter Luis Silva dead of heart attack at 64

ReactJS Fetched API data displays live - need Data displayed static

政党