Class in Python
Concept
Python is an object oriented programming language.
Almost everything in Python is an object, with its properties and methods.
A Class is like an object constructor, or a "blueprint" for creating objects.
A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to it for maintaining its state. Class instances can also have methods (defined by its class) for modifying its state.
Code Example
Example 1:
class Human:
pass
>>> o = Human()
>>> type(o)
<class '__main__.Human'>
Example 2:
class Student:
"""
Attributes & Methods
"""
def __init__(self, x=0, y="name"):
print("Creating Object For You")
self.roll = x
self.name = y
# Object Creation
o = Student()
print(o.roll)
print(o.name)
Example 3:
class Student:
count = 1
def __init__(self, x=0):
self.s_id = Student.count
self.roll = x
Student.count += 1
def print_data(self):
print("Id: ", self.s_id)
print("Roll : ", self.roll)
# Object Creation 1
o = Student(10)
o1 = Student(20)
o2 = Student(30)
# Object Creation 2
o.print_data()
o1.print_data()
o2.print_data()
Comments
Post a Comment