How to create and use a class in Python?

To create and use a class in Python, follow these steps:

Step 1: Create a class To create a class, use the class keyword followed by the name of the class. Inside the class, define the properties (attributes) and methods (functions).

class MyClass: def __init__(self, name): self.name = name def say_hello(self): print(f"Hello, {self.name}!")

In the above example, we define a class called MyClass with two methods: __init__ and say_hello. __init__ is a special method called a constructor, which initializes the attributes of the class.

Step 2: Create an instance of the class (Object) To use a class, you need to create an object (instance) of that class. You can create an object by calling the class name followed by parentheses.

my_object = MyClass("John")

In the above example, we create an object called my_object of the class MyClass and pass the name "John" as a parameter to the constructor.

Step 3: Access class attributes and methods You can access the attributes and methods of an object using the dot notation.

print(my_object.name) # Output: John my_object.say_hello() # Output: Hello, John!

In the above example, we access the attribute name and call the method say_hello() using the my_object object.

That's it! You have successfully created and used a class in Python.