Python working with classes and objects
In this article we will learn how to work with classes and objects in python. Python classes are mainly used for code reusability and better maintainability. You might have a question that we have a functions why do we need classes ? that's a good question. By using functions we can reuse the functionality In some cases we may need to hold the data and functionality together which is not possible with python functions. So, to bundle the data and functionality together we use python classes.we can use the object oriented programming principles like inheritance, encapsulation, etc. using python classes.
Syntax of a pyhon class
class <ClassName>: <statement-1> . . . <statement-n>
"class" is a keyword in python which is used to create a class.
Working with python class
class Snake: name = 'python' def change_name(self, new_name): self.name = new_name self.status = "name changed"
- Creating an object in python
obj = Snake()we have created an object of class "Snake". The process of creating a class object is called "instantiation". So, object of the class is also called as an instance of a class which is created from.
- Accessing the attribute of a class
obj = Snake() print(obj.name) #Output: pythonThe variables that are defined inside the class are called as "attributes". In python, we have two types of attributes 1. instance attribute 2.class attribute. In above example we have seen accessing the instance attribute. In the next example we will see how to access class attribute of a python class.
- Accessing the class attribute of a class. Class attribute is also called as class variable.
print(Snake.name) #Output: pythonIn the above code we have not created an object of the class. But, we are still able to access it. Because it is a class variable.
- Accessing the method of a class
obj = Snake() obj.change_name('Cobra') print(obj.name) #Output: CobraIn above code we have called the class method "change_name". In python we call the function as method if it is inside the class. In the method signature we have used "self" keyword of python. The keyword "self" is used inside the class definition. It is used to represent the instance of the class. It means it represents the object itself.