This is a detailed tutorial on Python Classes and Objects. Learn to do object-oriented programming in python using classes, objects, and their methods.
Python can be used to do object-oriented programming. Any variable, a function, or just anything that you can imagine in python that holds something is a python object. A python class can be defined as a data type, a structure, or a pattern that can be used to create objects. In many other programming languages, classes are defined as user-defined data types. But in python, even the in-built data types are defined with the label class. Therefore, Python classes can be defined as a blueprint.
Whenever you apply python’s in-built function on any object, let it be a variable or a function, you might have noticed the word class.
Example. Observe the following code snippet and its output.
x = 10 y = "Hello" def aFunction(): print("Hello") z = [1,2,3,4,5] print(type(x)) print(type(y)) print(type(aFunction)) print(type(z))
In the above code, we’ve defined four different python objects. You can see in the output that the type function tells the class of each of these objects.
Therefore, you can use the type() function to check the class of any python object. The above example basically illustrates the inbuilt classes. But you can also define your own classes and your own objects.
Creating Classes
Although there are a lot of inbuilt classes yet you might be wanted to create your own class. Well, you can create it by using the keyword class
and that’s pretty easy. The syntax is simple. You’ve to write the keyword class
followed by the class name and just after that, you’ve to type a semicolon, and in the next line tabbed space, the body of the class starts. It is similar to creating a code block for loops, while loops, if-else statements, and python functions.
Example. The following snippet of code illustrates how you can create a simple class named bio
.
class bio: name = "Gurmeet Singh" age = 21 print(bio)
The class bio
contains two properties, name
and age
and the values of these properties are assigned within the class.
In the output, you can see it prints __main__.bio
, this is the notation that is printed when you print a class.
Creating Objects
The objects of a class can easily be created as demonstrated in the following example.
Example. I’ve first defined a class named bio and then I’m creating an object, using which I’m fetching two different values.
class bio: name = "Gurmeet Singh" age = 21 #Creating a Python Class Object obj = bio() #Fetching values print(obj.name) print(obj.age)
Note. You can create any number of objects for a python class.
__init__()
Function
The __init__()
function is an inbuilt python function. It is always executed whenever a class is initialized. This is basically a method that can be written within a python class and it will automatically execute whenever you will create an object of the class. The __init__()
function is like the class constructor method in most other programming languages like Java. In practical applications involving python programs that are designed in an object-oriented way, it is highly used.
class myFirstClass: def __init__(self): print("My object is created!") obj = myFirstClass()
Note. You must always define a parameter named self inside the parenthesis of the function __init__()
, otherwise, it will give you a positional argument error. The argument self is always passed automatically whenever creating new objects of the class and it refers to the current class. It is like this variable in other object-oriented programming languages. But the difference is you need not say this keyword as self
always. You can write any variable name instead of self, it’s just that it has to be the first parameter of this function.
You can see when I created an object named obj
of the class myFirstClass
and the function __init__()
is automatically called. That’s why the print statement written inside the function is executed. This function is usually used to assign class values.
Therefore, this function also allows the data to be passed directly to the class using the class name as a function.
self
Parameter – Class Reference Variable
I’ve already mentioned that the first parameter of the function __init__ is used as the variable that refers to the current class like this keyword in many other object-oriented programming languages.
Example. The following example makes use of this function to assign values to the class variables name
and age
.
class myFirstClass: def __init__(self, name, age): self.name = name self.age = age obj = myFirstClass("Gurmeet Singh", 21) obj1 = myFirstClass("Amandeep Singh", 12) print(obj.name) print(obj.age) print(obj1.name) print(obj1.age)
In function __init__()
, I’ve assigned two parameters, name
and age
. Then I’m assigning the values referencing to the class variables using the class referencing variable self
. Then I created two different class objects obj
and obj1
, and passed different arguments for name and age to both of these. In the end, I’m simply printing the values using these objects.
Object Methods
The classes can also contain functions and the functions defined inside python classes are known as object methods. To call these functions outside the class, we need to refer to it by creating an object of the class, just like we access class object properties.
Example. In the following code snippet, I’ve created a class named greetings, and then I’ve created three different methods inside it.
class greetings: def __init__(self, name): self.name = name def morning(self): print("Good Morning " + self.name + "!") def noon(self): print("Good Afternoon" + self.name + "!") def evening(self): print("Good Evening" + self.name + "!") #Creating class object obj = greetings("Gurmeet Singh") #Calling class method obj.morning()
The class methods are morning(), noon(), and evening(). I’ve also defined the function __init__()
here to assign the value of the class property name while creating an object by passing it as an argument.
Similar to the function __init__()
, you must specify the first parameter as a variable that refers to the current class. Other than that, you can specify parameters to object methods like normal python functions.
Change Object Properties
The different properties of the objects can be changed using the objects themselves. It is similar to the way you fetch the object properties like we’ve done so the above examples and the difference is just that now you’ve to assign them a value using one of the assignment operators like =
.
Example. In the following example, we’re modifying the values for the two properties of the class that have some default values already set.
class myFirstClass: name = "Gurmeet Singh" age = 21 obj = myFirstClass() #Current Object Properties print(obj.name) print(obj.age) #Modifying Object Properties obj.name = "Amandeep Singh" obj.age = 12 #Changed Object Properties print(obj.name) print(obj.age)
I’ve created a class object obj and then printed down the default values of its properties then I’ve modified the values and again printed out them to see the change.
Deleting Classes and Object Properties
The properties of the class objects can easily be deleted using the keyword del
.
Example. In the following example, I’ve deleted a class property named age
using the del
keyword.
class myFirstClass: name = "Gurmeet Singh" age = 21 obj = myFirstClass() #Current Object Properties print(obj.name) print(obj.age) #Deleting Object Property age del obj.age print(obj.name) print(obj.age)
I’ve first printed the two properties of the object of the class myFirstClass
and then I used the del keyword to delete one of its properties and then again when I try to print that deleted property the python program raises an error.
Similarly, you can also use the keyword del
to delete the class itself as well.
Example. In the following snippet of code, we’ve deleted the class using the keyword del
.
class myFirstClass: name = "Gurmeet Singh" age = 21 print(myFirstClass) del myFirstClass print(myFirstClass)
We first printed the class, it prints well then after using deleting it when we tried to print the class, it raises an error because the class does not exist anymore.
Creating Empty Classes with pass
Statement
You can also define an empty class with no properties or any other logic. But to make the class block valid and to avoid the Python End of the File error, you must use the pass
statement inside the class block like we make use of it to create empty functions.
Example. In the following code snippet, we’ve created an empty class name justEmpty
.
class justEmpty: pass print(justEmpty)
We’ve also printed the class to show that it is a valid Python Class and yet contains no properties and code. You can still create its objects and can also create its properties and set their values.
I hope you found this guide useful. If so, do share it with others who are willing to learn Python. If you have any questions related to this article, feel free to ask us in the comments section.