python class keyword
Last Updated :
18 Dec, 2024
Improve
In Python, class keyword is used to create a class, which acts as a blueprint for creating objects. A class contains attributes and methods that define the characteristics of the objects created from it.
This allows us to model real-world entities as objects with their own properties and behaviors.
See the example below to understand how we can create class.
# Creating class
class Person:
def __init__(self, name):
self.name = name
# Method
def greet(self):
print(f"Hello {self.name}")
# Creating object
p = Person("shakshi")
# Method calling
p.greet()
Output
Hello shakshi
Explanation:
- This
Person
class defines an__init__
method to set thename
and agreet
method to print a greeting. - An object
p
is created with the name"shakshi"
.
Syntax of class Keyword:
class ClassName:
def __init__(self, attributes):
# Constructor to initialize attributes
self.attribute1 = attribute1
def method(self):
# Method definition
class:
This
defines a new class namedClassName
.def
__init__:
This is used to initialize the attributes of the class.self
: It refers to the instance of the class, allowing access to its attributes and methods.- Method: It is used to perform actions related to the class.