Python Classes and Objects

Python is an Object-Oriented Programming (OOP) language. A Class is a blueprint for creating objects, and an Object is an instance of a class. Creating a Class Use the class keyword to create a class. Syntax Example Creating an Object An object is created from a class. Example Output: Class Attributes Attributes are variables that […]

2 mins read Lesson 6 of 56 11% through track

Python is an Object-Oriented Programming (OOP) language. A Class is a blueprint for creating objects, and an Object is an instance of a class.

Creating a Class

Use the class keyword to create a class.

Syntax

class ClassName:
    pass

Example

class Student:
    pass

Creating an Object

An object is created from a class.

Example

class Student:
    pass

student1 = Student()

print(student1)

Output:

<__main__.Student object at 0x...>

Class Attributes

Attributes are variables that belong to a class.

Example

class Student:
    name = "John"
    age = 20

student1 = Student()

print(student1.name)
print(student1.age)

Output:

John
20

The init() Method

The __init__() method is a special method that runs automatically when an object is created.

Example

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

student1 = Student("John", 20)

print(student1.name)
print(student1.age)

Output:

John
20

Instance Methods

Methods are functions defined inside a class.

Example

class Student:
    def __init__(self, name):
        self.name = name

    def greet(self):
        print("Hello", self.name)

student1 = Student("John")

student1.greet()

Output:

Hello John

Modify Object Properties

Example

class Student:
    def __init__(self, name):
        self.name = name

student1 = Student("John")

student1.name = "Alice"

print(student1.name)

Output:

Alice

Delete Object Properties

Example

class Student:
    def __init__(self, name):
        self.name = name

student1 = Student("John")

del student1.name

Delete an Object

Example

class Student:
    pass

student1 = Student()

del student1

The self Parameter

The self parameter refers to the current object and is used to access object properties and methods.

Example

class Student:
    def __init__(self, name):
        self.name = name

    def show(self):
        print(self.name)

student1 = Student("John")

student1.show()

Output:

John

Summary

  • A class is a blueprint for creating objects.
  • An object is an instance of a class.
  • The class keyword is used to create classes.
  • The __init__() method initializes object properties.
  • Methods are functions defined inside a class.
  • The self parameter refers to the current object.
  • Object properties can be modified or deleted.