Classes

Classes

In Python, a class is a blueprint for creating objects, which are instances of the class. A class defines a set of attributes and methods that the objects created from it will have.

To define a class in Python, we use the class keyword followed by the class name and a colon. For example:

pythonCopy codeclass MyClass:
    # class definition goes here

Inside the class definition, we can define attributes and methods. Attributes are variables that hold the state of the object, while methods are functions that operate on that state.

Here’s an example of a class definition with some attributes and methods:

pythonCopy codeclass Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def say_hello(self):
        print(f"Hello, my name is {self.name} and I'm {self.age} years old.")
    
    def have_birthday(self):
        self.age += 1
        print(f"Happy birthday! You are now {self.age} years old.")

In this example, we define a class Person with two attributes, name and age, and two methods, say_hello() and have_birthday(). The __init__() method is a special method that gets called when we create a new instance of the class, and it initializes the attributes of the object.

To create an instance of a class, we call the class like a function, passing any required arguments. For example:

pythonCopy codep = Person("Alice", 25)

This creates a new instance of the Person class with the name “Alice” and age 25. We can then call the object’s methods, which will operate on the object’s attributes:

pythonCopy codep.say_hello()  # prints "Hello, my name is Alice and I'm 25 years old."
p.have_birthday()  # prints "Happy birthday! You are now 26 years old."

Overall, classes are an important concept in object-oriented programming, and they allow us to create complex data structures and abstractions in Python.

Apply for Python Certification!

https://www.vskills.in/certification/certified-python-developer

Back to Tutorials

Rapid STP IEEE 802_1w RSTP
Object methods and the init method

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?