tags:

views:

130

answers:

1

I'm trying to understand, is there any difference at all between these classes besides the name? Does it make any difference if I use or don't use the __init__() function in declaring the variable "value"?

class WithClass ():
    def __init__(self):
        self.value = "Bob"
    def my_func(self):
        print(self.value)

class WithoutClass ():
    value = "Bob"

    def my_func(self):
        print(self.value)

My main worry is that I'll be using it one way when that'll cause me problems further down the road (currently I use the init call).

+8  A: 

Variable set outside __init__ belong to the class. They're shared by all instances.

Variables created inside __init__ (and all other method functions) and prefaced with self. belong to the object instance.

S.Lott
variables prefixed with 'self' that is..
roe
That's not what python does for me. Lists/dicts/etc get shared between all instances if you don't create them in `__init__()`.
too much php
@too much php: All variables at the class method (irrespective of mutability -- lists and dicts are mutable) are shared. With immutable objects, the sharing isn't interesting. With mutable objects (lists and dicts) the sharing is significant.
S.Lott
I suspected that might be the case but figured that if I stated my assumptions it might distract from the question itself, cheers for clearing it up :)
Teifion