Here is the question of a python code asked on InfyTQ mock test.
class classOne:
__var_one = 1001
def __init__(self,var_two):
self.__var_two = var_two
self.__var_five = 5
def method_one(self):
var_four = 50
self.__var_five = ClassOne.__var_one + self.__var_two + var_four
Now, I want to ask if the variable
self.__var_five
of function method_one
should be considered a new instance variable or not?
Because there is already a self.__var_five
in __init__
function.
Also, I learned the concept of global,local,static and instance variable from given below code. Is it correct?
#global, local, static, instance variable.
#global variable are defined at the top of program or defined using keyword:global
global global_var1 = 0
global_var2 = 1
def local_variable:
#local variable are defined inside of a function.
local_var1 = 2
class static_instance:
#static/classs variable are defined inside of a class.
static_var1 = 3
def __init__(self):
#all variables defined in the function of a class starting with self.
self.instance_var1 = 4
def static(self):
self.instance_var2 = 5
local_var2 = 6 #local variable as it is in a function.
static_var2 = 6
It's the same instance variable (called an attribute in Python). method_one
is simply updating its value.
Most of your understandings in the second code block are correct. However, when a method does:
self.static_var1 = 4
it creates an instance attribute named static_var1
. This is independent of the class attribute that was declared outside the methods, which is shared among all instances that don't reassign it. But since you do the assignment in the __init__()
method, all instances get their own attribute. The only way to access the static value would be with static_instance.static_var1
.