Python Class

  • December 8, 2022
  • python
JOIN Clause

As we discussed in the previous tutorial, a class is a virtual entity that can be thought of as an object’s blueprint. The class was created when it was instantiated. Let us illustrate this with an example.

Assume a class is a building prototype. A building contains all the information about the floor, rooms, doors, windows, and so on. Based on these details, we can construct as many buildings as we want. As a result, the building can be viewed as a class, and we can create as many objects of this class as we want.

Syntax: Class Definition 

class ClassName:
    # Statement

Example:

Consider the following example to create a class Student which contains two fields student roll_num, and name.

The class also contains a function display(), which is used to display the information of the Student.

class Student:    
    roll_num = 10   
    name = "Devansh"    
    def display (self):    
        print(self.roll_num,self.name)   

This was how we define a class in python, now let’s understand how to create an instance/object of a class.

Creating object for a class:

When a class’s object is created, the class is said to be instantiated. The attributes and behavior of the class are shared by all instances. However, the values of those attributes, i.e. the state, are specific to each object. A single class can have an unlimited number of instances.

For Instance,

myObject = MyClass()

where MyClass is the name of the class and myObject is the object variable

Example:

class Fish:
	# A simple class
	# attribute
	kingdom = "pisces"
	name = "Fish"

	# A sample method
	def fun(self):
		print("I'm a", self.kingdom)
		print("I'm a", self.name)


# Driver code
# Object instantiation
obj1 = Fish()

# Accessing class attributes
# and method through objects
print(obj1.kingdom)
obj1.fun()
Output:
pisces
I'm a pisces
I'm a Fish
__init__ method:

The init method is similar to C++ and Java constructors. Constructors are used to set the state of an object. A constructor, like a method, contains a collection of statements (i.e. instructions) that are executed when an object is created. It starts when a class object is instantiated. The method is useful for performing any initialization on your object.

Example:

# Sample class with init method
class Student:

	# 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 = Student('Rohan')
p.say_hi()

Output:

Hello, my name is Rohan

Note: also read about Object-Oriented Programming in Python

Follow Me

Please follow me to read my latest post on programming and technology if you like my post.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Leave a Reply

Your email address will not be published. Required fields are marked *