There are two situations wherein you will access members of a class-
Members of a class | How to access those members from outside the class |
---|---|
Instance Variables | obj.variableName You will get error when you try to access instance variables via ClassName. |
Instance Methods | obj.methodName() You will get error when you try to access instance methods via ClassName. |
Class Variables | obj.variableName OR ClassName.variableName When you modify class variables using instance of a class then you end up creating an instance variable having the same name as that of a class variable for that object that is why it is always recommended to access class variables via class name instead of object. For more information, read this page- Class variables in Python | Static variables in Python |
Class Methods | obj.methodName() OR ClassName.methodName() |
Static Methods | obj.methodName() OR ClassName.methodName() |
Members of a class | Instance Variables | Instance Methods | Class Variables | Class Methods | Static Methods |
---|---|---|---|---|---|
Instance Variables | - | You can access instance variables inside instance methods like this- self.variableName |
- | They cannot access instance variables. | They cannot access instance variables. |
Instance Methods | - | They can call other instance methods like this- self.methodName() |
- | They cannot call instance methods. | They cannot call instance methods. |
Class Variables | - | Inside instance methods, you can access class variables using any one of the below syntax- type(self).variableName OR ClassName.variableName |
- | There are two ways to access class variables from the inside of class method- cls.variableName OR ClassName.variableName |
There is the only way to access class variables from the inside of static methods- ClassName.variableName |
Class Methods | - | Inside instance methods, you can call class methods using any one of the below syntax- self.methodName() OR ClassName.methodName() |
- | There are two ways to call class methods from the inside of class method- cls.methodName() OR ClassName.methodName() |
This is the only way to call class methods from the inside of static method- ClassName.methodName() |
Static Methods | - | You can call static methods from instance method by using any one of the below syntax- self.methodName() OR ClassName.methodName() |
- | There are two ways to call static methods from class method- cls.methodName() OR ClassName.methodName() |
Inside static method, you can call another static method using the below syntax- ClassName.methodName() |