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

brandon w thisisonlyatest at gmx.com
Thu Aug 4 02:49:47 CEST 2011


On 08/02/2011 09:09 PM, Brett Ritter wrote:
> 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
>
>    
I see that the name Fred was assigned to "instance.man" in the example 
that you gave. I did forget to put the quotes around the names to make 
them strings. I thought that those would compile. I just wanted to 
understand the reason why people would use "def __init__(self):" so that 
I know when to use it.

Thank you for your help.



More information about the Tutor mailing list