A Profound Introduction
Welcome to the most straightforward and intuitive blog on Object-Oriented Programming (OOP) that you'll ever find on dev.to. This blog series, Part #1, aims to provide you with a clear understanding of the subject.
Let's Begin
We'll start with a code block in Python:
l = [1, 2, 3, 4, 5]
print(l.upper())
What do you think the output would be? Surprisingly, this will result in an error:
'list' object has no attribute 'upper'
Now, let's focus on two critical terms here: "object" and "attribute."
You might be wondering why the error refers to the list: l
as an "object" when you have learned that a list is a datatype ๐ค. Additionally, what does "attribute" mean? Let's explore further with another code block:
l = [1, 2, 3, "oops"]
print(type(l))
# Output: <class 'list'>
Interesting, right? When we try to get the type of the list, it says "l
belongs to the class 'list'." But what is a "class" exactly?
Moments ago, we saw that an error mentioned that 'list' was an object. Let's clarify this confusion.
Class, Object, and Attributes
Here's the moment of truth: every datatype you've encountered in Python is, in fact, a class.
What is a class?
You can think of a class as a blueprint, but what do I exactly mean by a blueprint? We'll soon find out.
So, every datatype is a class, and whenever we create a variable of a class (datatype), it is referred to as an object
.
By the way, now that we know datatypes are classes, and since they were already present, datatypes are known as built-in classes. On the other hand, we have user-defined classes, which we'll explore in another blog.
Hence, if you try to print type(12)
, the output would be class <int>
. And if you create an object of the class/datatype int:
n = 1234 # n is an object of datatype int
print(n.append(1))
The above code will result in an error:
AttributeError: 'int' object has no attribute 'append'
This error informs us that the object we created n
is referred to as an object of the int
class/datatype.
In simpler terms, an object is an instance of a class.
We know that we can't append to an int, but why?
Because whoever created the class int
or datatype int
didn't add a functionality to do so. The functionality of an object, or the functions that we can perform on an object of a particular class, is called an attribute
.
In the above code's output, you may see the error message:
AttributeError: 'int' object has no attribute 'append'
This indicates that the int object n
here, of class int
, doesn't have any functionality to append.
That's all for now! We'll cover more topics soon, so stay tuned, buddy!
Top comments (2)
Thanks will keep looking out for your next posts
Thanks for appreciating ๐ซ