- Python Basics
- Python Home
- Python History
- Python Applications
- Python Features
- Python Versions
- Python Environment Setup
- Python Basic Syntax
- Python end (end=)
- Python sep (sep=)
- Python Comments
- Python Identifiers
- Python Variables
- Python Operators
- Python Ternary Operator
- Python Operator Precedence
- Python Control & Decision
- Python Decision Making
- Python if elif else
- Python Loops
- Python for Loop
- Python while Loop
- Python break Statement
- Python continue Statement
- Python pass Statement
- Python break Vs continue
- Python pass Vs continue
- Python Built-in Types
- Python Data Types
- Python Lists
- Python Tuples
- Python Sets
- Python frozenset
- Python Dictionary
- List Vs Tuple Vs Dict Vs Set
- Python Numbers
- Python Strings
- Python bytes
- Python bytearray
- Python memoryview
- Python Misc Topics
- Python Functions
- Python Variable Scope
- Python Enumeration
- Python import Statement
- Python Modules
- Python operator Module
- Python os Module
- Python Date & Time
- Python Exception Handling
- Python File Handling
- Python Advanced
- Python Classes & Objects
- Python @classmethod Decorator
- Python @staticmethod Decorator
- Python Class Vs Static Method
- Python @property Decorator
- Python Regular Expressions
- Python Send E-mail
- Python Event Handling
- Python Keywords
- Python All Keywords
- Python and
- Python or
- Python not
- Python True
- Python False
- Python None
- Python in
- Python is
- Python as
- Python with
- Python yield
- Python return
- Python del
- Python from
- Python lambda
- Python assert
- Python Built-in Functions
- Python All Built-in Functions
- Python print() Function
- Python input() Function
- Python int() Function
- Python len() Function
- Python range() Function
- Python str() Function
- Python ord() Function
- Python chr() Function
- Python read()
- Python write()
- Python open()
- Python Examples
- Python Examples
- Python Test
- Python Online Test
- Give Online Test
- All Test List
Python Classes and Objects
This article is created to deliver all the things about classes and objects in Python. This article deals with these topics, related to class and object:
- Creating a class
- Creating an object
- Accessing attributes of the class
- The __init__() method of class
- The self parameter in method of class
- Deleting an object
- Class and object example program
Classes is an object-oriented feature of Python, provides to create program in more organized way by putting data members and methods in one place. Class also helps in encapsulating functionality into objects.
Creating a Class in Python
To create a class in Python, we need to use the class keyword just like creating the function, using def keyword. Here is the syntax to create a class in Python:
class class_name:
statement(s)
A class contains attributes and behaviors. Here attributes referred to variables, whereas behavior referred as methods (functions).
For example, to create a class MYCLASS with few statements (attributes) and a method named myfun(). Here is the code:
class MYCLASS: num = 10 name = "Python" def myfun(self): print("I'm inside a \"myfun()\" method")
Creating an Object in Python
To create an object in Python, we need to use the name of the class, of which the object is going to create. Because we can not statically define the type of variable in Python. For example, the following code:
val = 10
makes the variable val of int type automatically. Because 10 is an integer. In the same way, following code:
val = 10.49
makes the variable val of float type. And the following code:
val = "python"
makes the variable val of string type. Therefore just like these things, we also can not define the type of object. Rather we need to initialize the class, of which the object is going to create. For example, the following code:
ob = MYCLASS()
makes the object ob of MYCLASS type. The () after MYCLASS is basically referred as constructor. As you can see, the syntax to create an object in Python is:
object_name = class_name()
Now let's create an example program, that prints the type of object, created of a class named MYCLASS:
class MYCLASS: def myfun(self): print("I'm inside the method \"myfun()\".") print("The method is inside the class \"MYCLASS\"") ob = MYCLASS() print(type(ob))
The above program produces the type of object ob as shown in the snapshot given below:
As you can see from the above output, the MYCLASS referred as the name of the class, object ob belongs to. Whereas the __main__ referred to module name.
For example, to create an object named obj of the class MYCLASS. Here is the code:
obj = MYCLASS()
Accessing Attributes of the Class
To access an attribute of a class in Python, here is the syntax:
object_name.variable_of_class
For example, to access attributes of the class MYCLASS, created above. Here is the code:
class MYCLASS: num = 10 name = "Python" obj = MYCLASS() print(obj.num) print(obj.name)
The above Python program produces the output as shown in the snapshot given below:
That is, you can access attributes of the class just by using the dot (.) operator after the object. Class methods can be accessed by using the class name. One class can have multiple objects. Different object have different behavior. So we need to pass the object. The syntax is:
class_name.method_name(object_name)
For example:
class MYCLASS: def myfun(self): print("I'm inside the method \"myfun()\".") print("The method is inside the class \"MYCLASS\"") ob = MYCLASS() MYCLASS.myfun(ob)
The output produced by above program on class and object in Python is:
Here ob passed to myfun() method of the class MYCLASS. That is, ob passed to MYCLASS.myfun() referred as a parameter. Therefore, this parameter (ob, the object) referred to self (parameter of myfun() method)
Another way to access the method of a class using its object is:
object_name.method_name()
For example:
class MYCLASS: def myfun(self): print("I'm inside the method \"myfun()\".") print("The method is inside the class \"MYCLASS\"") ob = MYCLASS() ob.myfun()
This program produces exactly same output as of previous program's output. From above program, the following statement:
ob.myfun()
states that the object ob gets passed as parameter to myfun(). As the ob object is of the class MYCLASS. Therefore, myfun() method of this class gets accessed. This is basically shortcut way to access the method of the class in Python. But I do not recommend to use this way for beginner. I recommend to use the previous way to access the method of a class using its object, for all beginner learner.
The __init__() Method of Class
In Python, the double underscore before and after the variable and method referred to special variable and method. So __name__ is a special variable, whereas __fun__() is a special method.
The __init__() method is like constructor. That is, upon creating an object of the class, automatically calls this method once. For example:
class MYCLASS: def __init__(self): print("I'm inside the method \"myfun()\".") print("The method is inside the class \"MYCLASS\"") ob = MYCLASS()
produces same output as of previous program. See, I've not called the method __init__(). I only created an object of the type MYCLASS. And this function automatically gets called after creating the object.
We can pass any number of arguments or parameters after self (self referred to object itself). For example:
class MYCLASS: def __init__(self, name, rollno): self.name = name self.rollno = rollno def myfun(self): print("Name =", self.name) print("Roll Number =", self.rollno) ob = MYCLASS("John Harvard", 468) MYCLASS.myfun((ob))
Here is its sample output:
In above program, inside the class, self referred to object. So using the following statements:
self.name = name self.rollno = rollno
initializes the value of name to a variable of current object. In the same way, in method myfun(), since name and rollno are not local variables. And since these two variables belongs to object, and self referred to the current object. So we need to use variables with self. For example, the following example uses two objects:
class MYCLASS: def __init__(self, name, rollno): self.name = name self.rollno = rollno def myfun(self): print("Name =", self.name) print("Roll Number =", self.rollno) ob1 = MYCLASS("John Harvard", 468) MYCLASS.myfun((ob1)) ob2 = MYCLASS("Jane Stanford", 4704) MYCLASS.myfun((ob2))
This program produces:
The above program can also be created as:
class MYCLASS: def __init__(self, name, rollno): self.name = name self.rollno = rollno ob1 = MYCLASS("John Harvard", 468) print("Name =", ob1.name) print("Roll Number =", ob1.rollno) ob2 = MYCLASS("Jane Stanford", 4704) print("Name =", ob2.name) print("Roll Number =", ob2.rollno)
That is, to create an instance of a class in Python, call the class using the class name and then pass the number of arguments, the __init__() method accepts. Here is an example.
stud1 = STUDENT("Matt Damon", 198349) stud2 = STUDENT("John F. Kennedy", 213590) stud3 = STUDENT("Al Gore", 189392)
Note - The method _init_() is a special method, called as class constructor or initialization method that Python calls when you create a new instance of the class. You are free to declare other class methods just like normal functions in Python.
The self Parameter of Method in Class
The self is basically referenced to the current object or instance of a class. It is used to access variables that belongs to the class.
Important - There is no need to use only self to reference the current instance of class. We can use any variable based on our need or mood or whatever you say. But the condition is, this must be available as the first parameter of method inside the class.
For example:
class MYCLASS: def __init__(cc, name, rollno): cc.name = name cc.rollno = rollno ob1 = MYCLASS("John Harvard", 468) print("Name =", ob1.name) print("Roll Number =", ob1.rollno)
produces:
Name = John Harvard Roll Number = 468
Note - But it is a better practice to use self, to avoid any misunderstanding for yourself, or for others who see your code.
Delete an Object in Python
To delete an object in Python, we need del keyword. Here is the syntax to delete an object in Python:
del object_name
For example:
class MYCLASS: def __init__(cc, name, rollno): cc.name = name cc.rollno = rollno ob1 = MYCLASS("John Harvard", 468) del ob1 print("Name =", ob1.name) print("Roll Number =", ob1.rollno)
produces:
Since the object, is deleted immediately after creating. Therefore accessing anything of the class, using the object, produces error as shown in the snapshot given above.
The Use of pass Statement in Class
Since the class's definition must not be empty. Therefore if you need to create a class for further or future use, and for now, you do not need to define or provide any attributes or methods or both for the class. Then you can use the pass statement or keyword to achieve this. So that the compiler does not produce any error message while executing the code. For example:
class class_name: pass
Python Class and Object Example
Now I think, you have got the complete understanding on classes and objects in Python. So let's finalize the thing by one last example given below:
class STUDENT: totalStudent = 0 def __init__(self, name, fee): self.name = name self.fee = fee STUDENT.totalStudent += 1 def displayStudent(self): print("Name:", self.name, end="") print("\tFee:", self.fee) stud1 = STUDENT("Matt Damon", 198349) stud2 = STUDENT("John F. Kennedy", 213590) stud3 = STUDENT("Al Gore", 189392) stud1.displayStudent() stud2.displayStudent() stud3.displayStudent() print("\nTotal Student = %d" % STUDENT.totalStudent)
Here is its sample output:
Note - The end parameter in print() is used, in above program, to skip insertion of an automatically newline.
In above program, the following statement:
print("\nTotal Student = %d" % STUDENT.totalStudent)
can also be moved inside any method of the class STUDENT. For example, the program given below produces same output as of previous program:
class STUDENT: totalStudent = 0 def __init__(self, name, fee): self.name = name self.fee = fee STUDENT.totalStudent += 1 def displayCount(self): print("\nTotal Student = %d" % STUDENT.totalStudent) def displayStudent(self): print("Name:", self.name, end="") print("\tFee:", self.fee) stud1 = STUDENT("Matt Damon", 198349) stud2 = STUDENT("John F. Kennedy", 213590) stud3 = STUDENT("Al Gore", 189392) stud1.displayStudent() stud2.displayStudent() stud3.displayStudent() stud1.displayCount()
You can call displayCount() method with any of the three objects say stud1, stud2, or stud3. Since the __init__() method automatically gets called after creation of each object of the same class. Therefore because I've created three objects, so the method gets called three times. That increments the value of variable totalStudent by 1 each time.
Here, the variable totalStudent is a class variable whose value is shared among all the instances of this class. This can be simply accessed as STUDENT.totalStudent from inside the class or from outside the class.
« Previous Tutorial Next Tutorial »
Follow/Like Us on Facebook
Subscribe Us on YouTube