Understanding the difference between Class Var and Instance Var is fundamental to OOP.
Class Var
Given a class Lang, as below
class Lang: |
The results will be
Because the vars printed are class variables, Class Var is associated with the Class Lang
Instance Var
Change the code
class Lang: |
Instance Var is associated with a specific Object. In this example, name is not a good practice for Class var.
As name is usually specific with a concrete object.
The lookup order
Go back to the code below
class Lang: |
print out the __dict__, lang1 is empty now
Let’s add back self
class Lang: |
Now lang1 has proper attributes.
Here’s a Pythonic system to look up variables:
- Python will start look for variables in the object
- If the object doesn’t contain the target variable, it will continue search for the variable on the Class level
- If the target variable is not found on the Class level, it will keep searching from the parent Class level if there’s inheritance
Self
selfis explicitly needed for instance attributes and methods- user don’t need to assign
selfmanually, it’s automatically done by python - similar to
thisin Java
class Lang: |
selfis the object that invokes the method at the moment, e.g. forlang1.check_version(),selfislang1in the case above
Access Instance Var and Class Var within Instance Methods
- instance methods: behavior
- instance vars: attributes
- instance methods usually would perform some operations on vars to change the states/results of vars, hence they need to access vars in classes or instances
__init__function is a special type of instance method. It defines and initializes the attributes of an instance
Instance methods to access instance vars,
self.varnameInstance methods to access class vars
class Lang: |
The print out results are misleading here, if we change the arg name to lang, print(name) will report error as name doesn’t exist any more
class Lang: |
- How to access the class var
count?
class Lang: |
It will still report name error
- To properly access the class var, the class name is needed
class Lang: |
- Magically
self.countis also accessible thanks to the order of looking var: instance then class then parent class
class Lang: |