Reputation: 17
In the example seen below, I have declared an object, obj1, using my class, Classy. When obj1 is initialized, I declare a variable using self.var and I have an instance object that I can print to the console. All straight forward.
My question is around the other variable I have set, named variable. Running my code produces no errors, but I have (seemingly) no way of accessing it. It is neither a class variable of Classy, nor an instance variable is obj1.
Where is variable?
class Classy:
def __init__(self, value):
self.var = value
variable = 1
obj1 = Classy("object")
print(obj1.var)
object
Upvotes: 1
Views: 813
Reputation: 11
The attribute "variable" is a local attribute that you can only access inside of the __init__() method. Indeed if you modify your class adding "print(locals)"
class classy:
def __init__(self,value):
self.var = value
variable = 1
print(locals())
you can see that this attribute exists inside of the method. But if you get an instance of your class and then write
c = classy(10)
print(c.__dict__)
or
print(dir(c))
you can see that "variable" is not declared in the instance scope. So, "variable" is still a dynamic attribute because you wrote it inside of a method (it is not static) but the difference between it and "var" is that you can only use "variable" inside of init() method.
You can try to write
class classy:
def __init__(self,value):
self.var = value
variable = 1
def __increment__(self):
self.var +=variable
c = classy(10)
c.__increment__() # NameError: name 'variable' is not defined
and see that you can neither use it inside of another method in the same class.
Upvotes: 1
Reputation: 715
Your variable named variable
is a local variable. Specifically, it's local to the __init__()
method. You won't be able to access it outside of that method. You can only access it inside of the method. Local variables created inside of the __init__()
method really only serve the purpose of creating other instance variables:
class Classy:
def __init__(self, value):
self.var = value
variable = 1
self.new_var = variable + 1 # new_var is 2
obj1 = Classy("object")
print(obj1.var)
Upvotes: 3
Reputation: 2153
the variable variable
is scoped to the function. when you return from the function it is gone.
Upvotes: 1