How to Create and Instantiate a Simple Class in Python
In this blog, we will learn how to create a simple class in Python and how to instantiate that class by objects. Before learning about this, we have to explore several terms to understand the topic better. Such as
What is Python?
What are Classes, Objects, Instances, Attributes, Self parameter, and Methods?
What is the _init_() method?
What is the _str_() method?
What are the Instance variable and Class variable?
Python
Python is an object-oriented programming language, in this everything is associated with objects and classes. Classes, a unique programming construct, are used to implement most of the code. A Python object, in general, is a collection of data elements and methods that describe the behaviour of those elements.
Python can operate on practically any platform, including Windows, all Linux distros (including all versions of Linux), Mac OS X, Unix, and many others. It can be used to create complicated programs as well as GUI (Graphical User Interface) based apps. Web applications can be developed on a server using Python.
Python is an interpretive language because the interpreter runs the Python code line by line, making debugging simpler. Python uses indentation to indicate a block of code. Python's indentation is important, unlike other programming languages where indentation just serves to make the code easier to read.
Class
A class is a user-defined blueprint or template from which objects are produced. Classes offer a way to group functionality and data. For instance,
The class can be compared to a blueprint or sketch of an apartment(object). It includes all the information regarding the floors, doors, windows, etc. We construct the residence based on these descriptions. We can build numerous objects from a class. Since numerous apartments can be created using the same description.
To construct a class in Python, use the “class” keyword. For example,
class ClassName:
# class definition
Let's consider this example,
class Lorry:
name = ""
gear = 0
Here,
Lorry - the name of the class.
name, gear - variables inside the class with default values " " and 0 respectively.
Let’s create a simple empty class in Python,
# Incorrect empty class in
# Python
class Geeks:
It will show a syntax error.
Output:
To create an empty class in Python, we use the “pass” statement. This is a special statement that does nothing. We can create objects for empty classes. For instance,
# Python program to demonstrate
# empty class
class Geeks:
pass
# Driver's code
obj = Geeks()
print(obj)
Output:
In Python, we can create attributes of an object of an empty class and we can create different attributes for the different objects as well. Look at the following example,
# Python program to demonstrate
# empty class
class Employee:
pass
# Driver's code
# Object 1 details
obj1 = Employee()
obj1.name = 'Nikhil'
obj1.office = 'GeeksforGeeks'
# Object 2 details
obj2 = Employee()
obj2.name = 'Abhinav'
obj2.office = 'GeeksforGeeks'
obj2.phone = 1234567889
# Printing details
print("obj1 Details:")
print("Name:", obj1.name)
print("Office:", obj1.office)
print()
print("obj2 Details:")
print("Name:", obj2.name)
print("Office:", obj2.office)
print("Phone:", obj2.phone)
# Uncommenting this print("Phone:", obj1.phone)
# will raise an AttributeError
Output:
Objects
An object is referred to as an instance of a class. Instance and object are used interchangeably. The realized version of the class is called an object.
Syntax to create an object:
objectName = ClassName()
Consider the below illustration,
# create a class
class Lorry:
name = ""
gear = 0
# create objects of class
lorry1 = Lorry()
Here, lorry1 is the object of the class.
An object includes
State: It is portrayed by an object's attributes. It additionally reflects an object's properties.
Behaviour: The methods of an object serve as a representation of behaviour. It also shows how one object reacts to other objects.
Identity: It gives an object a special name and makes it possible for one object to communicate with another.
Let’s look at this real-time example,
We will explore more about this in the following content, creating and instantiating a simple class in Python.
Attributes
The variables inside a class are known as attributes. The dot (.) operator can be used to access attributes, which are always public. To access the class attributes, we can use the objects.
For example,
# modify the name attribute
lorry1.name = "Force"
# access the gear attribute
lorry1.gear
Here, name and gear are class attributes that can be accessed by object lorry1 to change and access the value of attributes.
Methods
A Python class can also have a function definition. A method in Python is a function that is defined inside a class and is called when an instance of the class is called. The “def ” keyword allows you to specify as many methods in a class, as you like. The initial parameter for every method must be “self ”, which normally corresponds to the calling instance.
Let’s consider the below example,
# create a class
class Room:
length = 0.0
breadth = 0.0
# method to calculate area
def calculate_area(self):
print("Area of Room =", self.length * self.breadth)
# create an object of Room class
study_room = Room()
# assign values to all the attributes
study_room.length = 42.5
study_room.breadth = 30.8
# access method inside class
study_room.calculate_area()
Output:
Here,
Class name: Room
Attributes: length and breadth
Method: calculate_area()
Here, we've created an object from the Room class with the name study_room. After that, we applied values to the attributes such as length and width using the object. Note that we also called the method inside the class using the object.
study_room.calculate_area()
Here, we called the method using the dot (.) notation to execute the method’s statement by object study_room.
Self parameter
To access class-specific variables, use the self parameter, which is a reference to the currently running instance of the class. It need not be called self; you can give it any name you choose, but it must be the first parameter of any class-related function.
An additional first parameter in the method declaration is required for class methods. When we call the method, we don't supply a value for this parameter; Python takes care of that. Even if we have a method that doesn't accept any arguments, we still have one(self). In C++ and Java, this is comparable to this pointer and this reference.
For example,
Instead of "self," use "mysillyobject" and "abc":
class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age
def myfunc(abc):
print("Hello my name is " + abc.name)
p1 = Person("John", 36)
p1.myfunc()
The _init_() method
The __init__ () method is similar to constructors in C++ and Java. Constructors are assisted to initialize the object’s state. Similar to methods, a constructor also consists of a set of statements(i.e. instructions) that are executed at the time of Object creation. It runs as soon as an object of a class is instantiated. This method is useful to do any initialization you want to do with your object.
To assign values to object properties or do other tasks required when creating the object, use the __init__() method. The __init__() method takes the new object as its first argument, self. Then it sets any required instance attribute to a valid state using the arguments that the class constructor passed to it.
Consider the following example,
# Sample class with the init method
class Person:
# init method or constructor
def __init__(self, name):
self.name = name
# Sample Method
def say_hi(self):
print('Hello, my name is', self.name)
p = Person('Nikhil')
p.say_hi()
Output:
The _str_() method
The Python __str__ method returns the string representation of the object.
Syntax of _str_method:
object.__str__(self)
The object representation is returned as a string using the Python __str__ method. A human-readable format that can be used to show certain object information is what this method is designed to return.
The string representation of an object with the __str__() function:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name}({self.age})"
p1 = Person("John", 36)
print(p1)
Output:
Class variables and Instance variables
Class variables are variables whose value is assigned in the class, but instance variables are variables whose value is assigned inside a constructor or method with self. Class variables are used for attributes and methods that are shared by all instances of the class, whereas instance variables are used for data that is specific to each instance.
For example,
# Python3 program to show that we can create
# instance variables inside methods
# Class for Dog
class Dog:
# Class Variable
animal = 'dog'
# The init method or constructor
def __init__(self, breed):
# Instance Variable
self.breed = breed
# Adds an instance variable
def setColor(self, color):
self.color = color
# Retrieves instance variable
def getColor(self):
return self.color
# Driver Code
Rodger = Dog("pug")
Rodger.setColor("brown")
print(Rodger.getColor())
Output:
Create and Instantiate a Simple Class in Python
As we said earlier in this blog, a class is a blueprint of an object which is created using the class keyword and an object is an instance of a class. Object declaration is known as object instantiation. We have already explored what are objects, attributes, methods, class variables, instance variables, and so on. Now we will see how to create and instantiate a simple class in python using these components.
A new class produces a new type of object, enabling the creation of new instances of that type. Each instance of a class may have attributes connected to it to preserve its state. Class instances may also contain methods for changing their state that is defined by their class.
Let’s consider the following example,
Let's imagine you wanted to keep tabs on the number of dogs with various attributes, such as breed and age. If a list is utilised, the dog's breed and age might be the first and second elements, respectively. What if there were 100 different breeds of dogs? How would you know which element should go where? What if you wanted to give these dogs additional traits? This is disorganised and just what classes need.
The class produces a user-defined data structure that contains its data members and member functions and that can be accessed and used by making an instance(object) of the class.
Creating a class
# Python3 program to
# demonstrate defining
# a class
class Dog:
pass
In the aforementioned example, the class keyword denotes the creation of a class, followed by the class name (Dog in this case).
An instance is a clone of the class with actual values, whereas a class is essentially a blueprint. It is now a real dog, say a seven-year-old pug, and is no longer just an idea.
Although you can have numerous dogs to generate a variety of instances, you would be lost without the guidance of the class, if you didn't know what information was needed.
Object Declaration (Also called instantiating a class)
A class is said to be instantiated when an object belonging to a class is created. The attributes and behaviours of a class are shared by all instances. However, the states of those attributes, or their values, are particular to each object. Any number of instances may exist for a single class.
# Python3 program to
# demonstrate instantiating
# a class
class Dog:
# A simple class
# attribute
attr1 = "mammal"
attr2 = "dog"
# A sample method
def fun(self):
print("I'm a", self.attr1)
print("I'm a", self.attr2)
# Driver code
# Object instantiation
Rodger = Dog()
# Accessing class attributes
# and method through objects
print(Rodger.attr1)
Rodger.fun()
Output:
An object (Rodger) the dog is built in the example above. In this class, Rodger is identified as a dog and a mammal by just two class attributes.
Class creation and instantiation using class and instance variables
# Python3 program to show that the variables with a value
# assigned in the class declaration, are class variables and
# variables inside methods and constructors are instance
# variables.
# Class for Dog
class Dog:
# Class Variable
animal = 'dog'
# The init method or constructor
def __init__(self, breed, color):
# Instance Variable
self.breed = breed
self.color = color
# Objects of Dog class
Rodger = Dog("Pug", "brown")
Buzo = Dog("Bulldog", "black")
print('Rodger details:')
print('Rodger is a', Rodger.animal)
print('Breed: ', Rodger.breed)
print('Color: ', Rodger.color)
print('\nBuzo details:')
print('Buzo is a', Buzo.animal)
print('Breed: ', Buzo.breed)
print('Color: ', Buzo.color)
# Class variables can be accessed using class
# name also
print("\nAccessing class variable using class name")
print(Dog.animal)
Output:
Delete the object in a class
We can remove the properties of the object or object itself by using the “del” keyword.
For instance,
class Employee:
id = 10
name = "John"
def display(self):
print("ID: %d \nName: %s" % (self.id, self.name))
# Creating an emp instance of Employee class
emp = Employee()
# Deleting the property of the object
del emp.id
# Deleting the object itself
del emp
emp.display()
Since we deleted the object emp, it will encounter the Attribute Error.
Conclusion
In this blog, we have gone through creating classes, instantiating objects, initializing attributes with the constructor method, and instantiating more than one object in the same class. Now that you have this knowledge to develop your class constructors and have complete control over instance generation and initialization in your Python object-oriented programming projects.
Understanding object-oriented programming is crucial because it makes it possible to reuse code by allowing objects created for one program to be used in another. Since complicated systems are challenging to build and need careful planning, object-oriented programming also results in better program design, which reduces the amount of effort required to maintain the program over time.
Python nomenclature
Comments
Post a Comment