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.
Instance variables − Instance variables are declared in a class, but outside a method.
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.
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.
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.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With