- Inside the constructor using
self. - Inside an instance method using
self. - Outside the class using the object reference variable.
Inside the constructor using self.
class Test: def __init__(self): self.a = 10 self.b = 15 obj = Test() # a , b will be added the object. print(obj.__dict__) # {'a': 10, 'b': 15}
Inside an instance method using self.
- We can declare instance variables inside an instance method using the
selfvariable. - If we declare an instance variable inside an instance method, that variable will be added to the object when the method is called.
- If the instance method is not called, those variables will not be added to the object.
class Test: def __init__(self): self.a = 10 self.b = 15 def m1(self): self.c = 25 obj = Test() # a , b will be added the object. obj.m1() # c will be added to the object print(obj.__dict__) # {'a': 10, 'b': 15, 'c': 25}
Outside the class using the object reference variable.
class Test: def __init__(self): self.a = 10 self.b = 15 def m1(self): self.c = 25 obj = Test() # a , b will be added the object. obj.m1() # c will be added to the object obj.d = 35 # d will be added to the object print(obj.__dict__) # {'a': 10, 'b': 15, 'c': 25, 'd': 35}