Introduction to Object Oriented Programming
Programming paradigms are a way to classify programming languages based on their features. Languages can be classified into multiple paradigms. One of the most common paradigms is Object-Oriented programming. This paradigm is based on the use of objects that can contain data and code. Python is an interpreted high-level Object-Oriented Programming language (OOP). With the exception of control flow, everything in Python is an object - the integers, strings, the funcions etc.
What is an Object?
Object is an entity with a unique identifier that is characterized by its properties and behavior:
- Properties (attributes) - describe the data stored in the object.
- Behavior (methods) - describes the methods (functions) in the object interface through which the object can be used.
This concept might sound a bit complex at first so let’s start with an example:
The type string is a class. Anytime we create a new string, we create a new object (or a new instance) of the string class. Therefore, this object has the same behavior of all the other strings:
- We can use the upper method.
- We can use index method.
- We can concatenate two strings using the + operator.
- We can use all the methods of the string class!
#String Class #Here we create the instance my_string = "This is a string object" print(type(my_string))
In the next tutorial we create our own class and things are going to be much clearer :)
The dir() Function
The dir() function is a built-in function. We can find all the methods of any object using the dir() function. It can be very useful!
#String Class #Here we create the instance my_string = "This is a string object" print(dir(my_string))
Dunder Methods __method__
Dunder methods ("Double Under") also referred as magic methods are reserved for special use in the Python. In many cases they are used for operator overloading. This methods start and end with double underscores. Please notice - it is best practice to avoid calling dunder methods directly (tough it is possible). The use of dunder methods is internall (commonly used for operator overloading).