Classes why __init__ sometimes and sometimes not?


#1

Ok this might be an odd question but I am trying to wrap my head around this whole OOP concept.

Why do some classes have a constructor and some do not? Is it because some classes you don’t actually want to create an instance of that class, you simply just want a group together a set of methods to use?

I’m unclear why at times you would actually want to create an object from a class, and sometimes you wouldn’t?


#2

we can perfectly create a instance of a class which doesn’t have an init method:

class Example(object):
   def example_method():
       print "see? no init method"

example = Example()

some classes might not need a constructor, there isn’t a rule for this. Its important to understand what a constructor is and what it does

but wether or not your class needs a constructor, is depending on the design and implementation choice a software developer has to make


#3

I totally understand that we don’t need a constructor in all classes. That is my question, why sometimes do I use one and sometimes I do not?

Is there any good documentation you can point me to that explains why I would or would not use a constructor?


#4

I covered this in my answer? There isn’t a rule for this. Its the programmers job (in this case you) to determine wether or not a constructor is required, which depends on many factors on what your class (and the rest of the program) needs to do, and how you are going to solve this problem and implement the solution, and wether or not this requires constructors, and if so, for what classes.

now, within the exercises, you don’t have much of a choice. The exercise has chosen for you.

if you think rules do exist for it, feel free to google, see what you come up with


#5

I did not mean is there a rule. I was looking for more of an example of why or why not I would need / want a constructor.


#6

You can look at open source python projects (on github for example), see some implementations.

But this is mostly just practice, build programs to familiarize yourself with this knowledge.


#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.