How to Create a Python Class?

Estimated read time 2 min read

To create a Python class, you use the class keyword, followed by the name of the class. Here’s an example:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def introduce(self):
        print(f"Hi, my name is {self.name} and I'm {self.age} years old.")

In this example, we define a Person class with an __init__() method and an introduce() method.

The __init__() method is a special method that gets called when a new object of the class is created. It takes two arguments, name and age, and assigns them to instance variables of the same names using the self keyword.

The introduce() method takes no arguments and uses the instance variables name and age to print a message introducing the person.

To create a new Person object, you would call the class constructor, like this:

person1 = Person("Alice", 25)

This creates a new Person object with the name “Alice” and age 25. You can then call the introduce() method on this object to print the introduction message:

person1.introduce()

This would output the message “Hi, my name is Alice and I’m 25 years old.”

You can customize this example to add additional methods and instance variables to the Person class, or create your own custom classes to model other objects or concepts in your Python programs.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply