DevAcademia
C++C#CPythonJava
  • Python Fundamentals

  • Introduction to Python
  • Getting Started with Python
  • Python Syntax
  • Python Comments
  • Python Variables
  • Python Data Types
  • Python Numbers
  • Python Casting
  • Python Strings
  • Python Booleans
  • Python Operators
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python If...Else
  • Python Match
  • Python While Loops
  • Python For Loops
  • Python Functions
  • Python Lambda
  • Python Arrays
  • Python OOP

  • Python OOP
  • Python Constructors
  • Python Destructors
  • Python Classes/Objects
  • Python Inheritance
  • Python Polymorphism
  • Python Quiz

  • Python Fundamentals Quiz
  • Python Fundamentals

  • Introduction to Python
  • Getting Started with Python
  • Python Syntax
  • Python Comments
  • Python Variables
  • Python Data Types
  • Python Numbers
  • Python Casting
  • Python Strings
  • Python Booleans
  • Python Operators
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python If...Else
  • Python Match
  • Python While Loops
  • Python For Loops
  • Python Functions
  • Python Lambda
  • Python Arrays
  • Python OOP

  • Python OOP
  • Python Constructors
  • Python Destructors
  • Python Classes/Objects
  • Python Inheritance
  • Python Polymorphism
  • Python Quiz

  • Python Fundamentals Quiz

Loading Python tutorial…

Loading content
Python OOPTopic 74 of 77
←PreviousPrevNextNext→

Python Classes and Objects

Classes and Objects Fundamentals

A class is a blueprint for creating objects. An object is an instance of a class that bundles together data (attributes) and behavior (methods).

Example
# Class definition and object creation
class Dog:
    # Class attribute (shared by all instances)
    species = "Canis familiaris"
    
    # Constructor method
    def __init__(self, name, age, breed):
        # Instance attributes (unique per object)
        self.name = name
        self.age = age
        self.breed = breed
    
    # Instance method
    def bark(self):
        return f"{self.name} says woof!"
    
    def get_info(self):
        return f"{self.name} is a {self.age}-year-old {self.breed}"
    
    # Special method for string representation
    def __str__(self):
        return self.get_info()

# Creating objects (instances)
dog1 = Dog("Buddy", 3, "Golden Retriever")
dog2 = Dog("Lucy", 5, "Poodle")

# Accessing attributes and methods
print(dog1.name)
print(dog2.species)
print(dog1.bark())
print(dog2.get_info())
print(dog1)  # Calls __str__ method
Output
Buddy
Canis familiaris
Buddy says woof!
Lucy is a 5-year-old Poodle
Buddy is a 3-year-old Golden Retriever

Class Components

ComponentDescriptionExample
Class AttributesVariables shared across all instancesspecies = "Canis familiaris"
Instance AttributesVariables unique to each objectself.name = name
MethodsFunctions that define object behaviordef bark(self):
ConstructorSpecial method called when creating objectsdef __init__(self, name, age):
Special MethodsEnable built-in operations__str__, __len__

Access Modifiers

Python does not enforce access restrictions strictly. Instead, naming conventions are used to signal intended access levels:

Example
# Access modifier conventions in Python
class Employee:
    def __init__(self, name, salary):
        self.name = name          # Public attribute
        self._department = "IT"   # Protected attribute (convention)
        self.__salary = salary    # Private attribute (name mangling)
    
    def get_salary(self):
        return f"Salary: ${self.__salary}"
    
    def _get_department(self):
        return self._department

emp = Employee("John", 50000)

# Public
print(emp.name)

# Protected (accessible but discouraged)
print(emp._department)

# Private (raises AttributeError if accessed directly)
print(emp.get_salary())

# Name mangling (not recommended)
print(emp._Employee__salary)
Output
John
IT
Salary: $50000
50000

Special Methods

Special methods (also called dunder methods) let objects integrate with Python’s built-in operations and operators.

Example
# Example of special methods
class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    
    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)
    
    def __sub__(self, other):
        return Vector(self.x - other.x, self.y - other.y)
    
    def __mul__(self, scalar):
        return Vector(self.x * scalar, self.y * scalar)
    
    def __str__(self):
        return f"Vector({self.x}, {self.y})"
    
    def __len__(self):
        return 2  # Always two components

v1 = Vector(2, 3)
v2 = Vector(1, 4)

print(v1 + v2)
print(v1 - v2)
print(v1 * 3)
print(len(v1))
Output
Vector(3, 7)
Vector(1, -1)
Vector(6, 9)
2
Test your knowledge: Python Classes and Objects
Quiz Configuration
4 of 8 questions
Sequential
Previous allowed
Review enabled
Early close allowed
Estimated time: 5 min
Python OOPTopic 74 of 77
←PreviousPrevNextNext→