Classes and Objects

Learn Python classes and objects with examples. Understand how to define a class, create objects, use attributes, and the self parameter in Python OOP.

Loading...
Classes and Objects

Defining a Class

A class in Python is defined using the class keyword. It can contain attributes and methods that define the behavior and characteristics of objects created from the class.

class Person:
    name = "John"
    age = 30

Creating an Object

An object is an instance of a class. Objects can be created by calling the class.

person1 = Person()  # Creates an object of the Person class

Accessing Class Properties

You can access attributes and methods of an object using the dot (.) operator.

print(person1.name)  # Output: John
print(person1.age)   # Output: 30

The self Parameter

In Python, the self parameter is a reference to the current instance of the class. It is used within the class to access attributes and methods.

class Person:
    def greet(self):
        print("Hello, I am", self.name)
 
person1 = Person()
person1.name = "Alice"
person1.greet()  # Output: Hello, I am Alice

👉 Next tutorial: Python Constructors

Support my work!