Class is used to create complex structures in Python. A class is used to specify the structure of an object or instance that contains public and private variables, and functions. The class is used to create or initialize instances. Before creating an instance we should define a class. In this tutorial, we examine how to define a class in Python.
Python uses the
class keyword for the class definition. Then the name of the class is provided and the first line of the class definition ends with the colon. the class body is put after the first line with indents which is defined according to the developer usage.
class CLASS_NAME: CLASS_BODY
- CLASS_NAME is the name of the class.
- CLASS_BODY is single or multiple lines to define class contents like variables, and methods.
In the following example, we create a very simple class named
person with some variables and methods. We will examine the variable and methods below.
class Person: name="İsmail Baydan" def name(): print(self.name)
Define Empty Class
While creating classes we can define an empty class and fill its content later. The
pass statement is used to fill the content with emptiness. In the following example, we use the pass statement in order to define a class that is empty.
class Person: pass
Classes are created to store some data and process this data. The variables are used to store and process data in the Python class. We can add a class variable like a regular variable definition inside the class. In the following example, we add the variable “age” to the “Person” class.
class Person: name="İsmail Baydan" age=38
Classes are generally used with their methods in order to process internal or external data and information. We can define a class with its method.
class Person: name="İsmail Baydan" age=38 def print_name(): print(self.name)
Initialize Class with __init__
Class is just a structure or plan for an instance. We can set some values and execute some tasks during the instance initialization. The
__init__ method is used to initialize the class. The
self and other required parameters are provided to the __init__ method. The self is used to access instance local variables and methods.
class Person: name="İsmail Baydan" age=38 def __init__(self,name): self.name=name self.age=age def print_name(): print(self.name)
Create Instance from Class
After defining a class we generally create instances from this class. In the following example, we create instances from the class Person by providing the initialization values.
class Person: name="" age=38 def __init__(self,name,age): self.name=name self.age=age def print_name(): print(self.name) ismail = Person("İsmail Baydan",38)