[Tutor] When to use def __init__ when making a class?

Brett Ritter swiftone at swiftone.org
Wed Aug 3 03:09:01 CEST 2011


On Tue, Aug 2, 2011 at 8:47 PM, brandon w <thisisonlyatest at gmx.com> wrote:
> 1)  When should I use "def __init__(self):" when I create a class?

When you have any initialization to do.  (in other words, when you
want class instantiation to do more than simply give you an instance
of the class.

> 2)  Would these two classes have the same effect?

Neither of these two classes compile.  You should try what you are
asking before asking, it will lead you to better questions.

Your examples show some misunderstanding about Python classes.

1)  an __init__ method shouldn't return anything.  The Class
construction call will already return an instance of the class,
__init__ is just about initialization.
2) A class definition likewise has no return value.
3) In your examples, Marcus and Jasmine are either intended to be
strings (and should be quoted), or are variables you didn't provide.

Here, try running these examples and see what you can figure out.
Experiment with them a little, then come back with questions on what
you observe.

class Name:
  def __init__(self):
    self.man = "Marcus"
    self.woman = "Jasmine"

instance = Name()
print instance.man  # Python 3 will use a different print syntax

class Name:
  pass

instance = Name()
instance.man = "Fred"
print instance.man

-- 
Brett Ritter / SwiftOne
swiftone at swiftone.org


More information about the Tutor mailing list