Python Class
About Python Class
Python supports object-oriented programming (oop) and class is the fundamental of oop.
A class is a user-defined blueprint (template) for creating object.
Class provides a means of bundling data and functionality together. In other words, attributes (variables) and methods (functions) are defined in the class which can be used when objects are created.
Typical syntax of Python class
-
class ClassName: The 'class' keyword defines the class named 'ClassName' which will be repalced by your class name. -
def __init__(self, name):: The 'def' keyword defines the __init__ method which is a special method in Python, known as a constructor. It is called automatically when a new instance of the class is created. 'self' represents the instance of the class. It is used to access variables and methods that belong to the class. 'name' is a parameter that needs to be passed to the __init__ method when an instance (object) of the class is created. -
self.attributeName = name: An instance variable named 'attributeName' is created which will be replaced by user defined name. The value of 'name' is set to the 'attributeName'. When an instance of 'ClassName' is created, the __init__ method is called with the argument 'name'. -
def methodName(self, parameter):: The 'def' keyword defines a method named 'methodName'. 'self' refers to the instance of the class on which the method is called. ' parameter' is a parameter that the method accepts. -
#code of method: This will be replaced by the code of your method.
Use the '@staticmethod' decorator for static methods that don't need access to instance or class attributes.
Use the '@classmethod' decorator for class methods that need access to class attributes but not instance attributes. It takes "cls" (the class name) as its first parameter.
Create Python class
Following is a typical example of creating and using a Python class with instance attributes and methods.
An instance of a class is an individual object created from the class blueprint. It has its own unique identity and can have different attribute values than other instances of the same class.
Example of Python class
Output of the above example
John speaks English.
John is 25 years old.
Explanation of example:
-
class Person:The 'class' keyword defines a class named 'person'. Semi-colon is the part of Python syntax. -
def __init__(self, name, age):: The 'def' keyword defines the __init__ method which is a special method in Python, known as a constructor. 'self' represents the instance of the class. 'name' and 'age' are two parameters. -
self.name = name and self.age = age: 'self.name' and 'self.age' are two class attributes assigned the value of 'name' and the value of 'age' respectively. -
def speak(self):: This defines an instance method named 'speak()'.print(f"{self.name} speaks English.")is the code of the method. -
def aboutPerson(self):: This defines an instance method named 'aboutPerson()'.print(f"{self.name} is {self.age} years old.")is the code of the method. -
personObj = Person("John", 25): The line is used to create an instance of the Person class and assign it to the variable personObj. 'Person("John", 25)' calls the constructor of the Person class with the arguments "John" and 25. This initializes the 'self.name' attribute with "John" and 'self.age' attribute with 25 for the personObj instance. -
personObj.speak() and personObj.aboutPerson()calls the 'speak()' and 'aboutPerson()' method of the personObj instance. The 'speak()' method prints "John speaks English." and the 'aboutPerson()' method prints "John is 25 years old."
Instance attributes of Python class
In Python, instance attributes are variables that are bound to a specific instance of a class. When object of a class is created, arguments for the variables are passed with the class instance.
These attributes are defined and initialized in the __init__ method of the class.
Example of instance attributes of a class
Output of the above example
Mike is 35 year old.
Explanation of example:
-
def __init__(self, name, age):The 'def' keyword defines the __init__ method. 'self' represents the instance of the class. 'name' and 'age' are two parameters which will be used to initialize the 'self.name' and 'self.age' attribute of the instance. -
self.name = name and self.age = age: These initialize the 'self.name' and 'self.age' attribute of the instance. -
personObj = Person("Mike", 35): The line is used to create an instance of the Person class and assign it to the variable personObj. 'Person("Mike", 35)' calls the constructor of the Person class with the arguments "Mike" and 35. -
print(f"{personObj.name} is {personObj.age} year old."): The line prints the values of instance attributes (variables).
Class attributes of Python class
In Python, class attributes are variables that are defined within the body of a class (not within any method in a class).
Any changes to a class attribute will be reflected across all instances.
Example of class attributes of a class
Output of the above example
Jenny is 20 years old.
Explanation of example:
-
name = "Jenny": 'name' is a class attribute initialized with "Jenny". -
age = 20: 'age' is another class attribute initialized with 20. -
print(f"{Person.name} is {Person.age} years old."): The line prints the values of class attributes (variables).
Instance methods of Python class
In Python, instance methods are functions defined within a class using 'self' as first parameter. It operates on instances of the class.
'self' allows access to the attributes and other methods of the instance. It can take other parameters along with the 'self' parameter.
Example of instance method of a class
Output of the above example
The full name of the person is John Taylor Abrams.
Explanation of example:
-
def fullName(self, middleName):'def' keyword defines an instance method named 'fullName' using 'self' as first parameter and 'middleName' as second parameter. 'self' allows access to the attributes and other methods of the instance. -
return self.firstName + " " + middleName + " " + self.lastName: The line returns full name of a person by concatenating the instance attributes 'self.firstName' and 'self.lastName' and parameter 'middleName'. -
personObj = Person("John", "Abrams")): The line is used to create an instance of the Person class and assign it to the variable personObj. 'Person("John", "Abrams")' calls the constructor of the Person class with the arguments "John" and "Abrams". -
print(f"The full name of the person is {personObj.fullName("Taylor")}."): The line prints full name of a person by passing 'Taylor' as value of the middleName parameter to the 'fullName()' method.
Class methods of Python class
In Python, class method is a function defined within a class using 'cls' as first parameter. It operates on the class itself.
'@classmethod' decorator is used to define a class method.
'cls' allows access to the attributes and other methods of the class. It can take other parameters along with the 'cls' parameter.
The class method can be called using the class name directly without creating an instance of the class.
Example of class method of a class
Output of the above example
The full name of the person is Mike Johnson Smith.
Explanation of example:
-
firstName = "Mike": 'firstName' is a class attribute initialized with "Mike". -
lastName = "Smith": 'lastName' is another class attribute initialized with "Smith". -
@classmethod: is a decorator placed before class method. It ensures that the following method is a class method. -
def fullName(cls, middleName):: The line defines a class method named 'fullName' by passing 'cls' as first parameter and 'middleName' as second parameter. 'cls' ensures access to the attributes and other methods of the class. -
return cls.firstName + " " + middleName + " " + cls.lastName: The line returns full name of a person by concatenating the class attributes 'cls.firstName' and 'cls.lastName' and parameter 'middleName'. -
print(f"The full name of the person is {Person.fullName("Johnson")}."): The line prints full name of a person by passing 'Johnson' as value of the middleName parameter to the 'fullName()' method. 'Person.fullName("Johnson")' calls the method using class name directly.
Static methods of Python class
In Python, static method is a function defined within a class that does not operate on the class or instance of the class.
Static method is often used as utility function that performs a task in isolation.
'@staticmethod' decorator is used to define a static method.
Static method can be called using the class name directly without creating an instance of the class.
Example of static method of a class
Output of the above example
The sum is 12
Explanation of example:
-
@staticmethodis a decorator placed before static method. It ensures that the following method is a static method. -
def addNumber(num1, num2):: The line defines a static method named 'addNumber' by passing two parameters 'num1' and 'num2'. -
return num1 + num2: The line returns the sum of two numbers. -
result = MathClass.addNumber(5, 7): 'MathClass.addNumber(5, 7)' calls the method passing arguments '5' and '7' and assign the returned value to the 'result' variable. -
print(f" The sum is {result}"): The line prints the result.
Python Compiler For Live Practice
Practice the above Python code in the following Python Editor. Create more Python class with different attributes and methods in the following Python code editor and click Execute button to check the output. Output will be displayed in Python Code Output section.
Python Editor