Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between variables inside and outside of __init__()

Is there any difference at all between these classes besides the name?

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) 

Does it make any difference if I use or don't use the __init__ method for declaring the variable value?

My main worry is that I'll be using it one way, when that'll cause me further problems down the road.

like image 508
Teifion Avatar asked Oct 08 '09 11:10

Teifion


People also ask

Are the variables declared within the class but outside the member method?

Instance variables − Instance variables are declared in a class, but outside a method.

How do you define a variable outside the class?

Variable defined inside the method: The variables that are defined inside the methods can be accessed within that method only by simply using the variable name. Example – var_name. If you want to use that variable outside the method or class, you have to declared that variable as a global.

How do you declare a static variable in Python?

When we declare a variable inside a class but outside any method, it is called as class or static variable in python. Class or static variable can be referred through a class but not directly through an instance.


2 Answers

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.

like image 88
S.Lott Avatar answered Sep 23 '22 06:09

S.Lott


Without Self

Create some objects:

class foo(object):     x = 'original class'  c1, c2 = foo(), foo() 

I can change the c1 instance, and it will not affect the c2 instance:

c1.x = 'changed instance' c2.x >>> 'original class' 

But if I change the foo class, all instances of that class will be changed as well:

foo.x = 'changed class' c2.x >>> 'changed class' 

Please note how Python scoping works here:

c1.x >>> 'changed instance' 

With Self

Changing the class does not affect the instances:

class foo(object):     def __init__(self):         self.x = 'original self'  c1 = foo() foo.x = 'changed class' c1.x >>> 'original self' 
like image 40
northben Avatar answered Sep 24 '22 06:09

northben