Python Classes Objects
What are objects?
Python is not purely an object-oriented programming language, but everything in Python is an object. Classes and objects in Python play a major role in higher-level development.
An object is the basic building block of an object-oriented programming language. Integers, strings, arrays, floats, lists, etc., these are all objects. If we have to be more specific, every single integer, or any substring is an object.
You have been using objects from the beginning of your Python learning journey and might have not realized it yet. The number 13 is an object, the string that you printed for the first time on your screen “Hello, World!” is an object.
To have a formal definition, we can say that an object in Python is basically a collection of various attributes and methods that are doing some operation with any kind of information.
In this tutorial, you are going to understand the basic concept of what objects are, how to create them, and most importantly how to use classes and objects together.
Objects and Instances
All objects in Python have their own types, and the type actually defines what can be done with that object. For example, the type int defines that whatever operation that can be performed on an integer can also be performed on an int.
An Instance: The word instance is many times used interchangeably with “object”. When you create an instance of a class, it means that you are creating an object.
Now, when you create an instance, for example, “Hello, World!” is an instance of the string type, the type string is used to instantiate the object.
There are two main characteristics of an object
- Property, and
Property: When you create an object, any instance or variable that gets associated to the object becomes the object’s property.
Behavior: Any instance or methods in the class that is associated with the object are the object’s behavior.
The attribute speech and name are the property of the object and the method that we defined as answer() and print_conv() are its behavior.
The self parameter
The code above does not print anything for now.
How to use objects
We have created a class with some methods in it, now to use the methods and attributes, let us create an object.
Let us understand how the object is working:
- In the first line, we use the class name to create an object, this is called Formally, we can say that we have created an instance of the class.
- In the second line, we use the dot (.) operator to access the method present in the class.
Try creating your own objects and classes in Python and practice a lot.