Classes and Objects

Defining classes and creating objects

Interview Relevant: Core OOP concept

Classes and Objects

Classes are blueprints for creating objects.

Code Examples

Basic class definition and instantiation.

python
1class Dog:
2    # Class attribute (shared)
3    species = "Canis familiaris"
4
5    # Constructor
6    def __init__(self, name, age):
7        self.name = name  # Instance attribute
8        self.age = age
9
10    # Instance method
11    def bark(self):
12        return f"{self.name} says Woof!"
13
14# Create objects
15dog1 = Dog("Buddy", 3)
16dog2 = Dog("Lucy", 5)
17
18# Access attributes
19print(dog1.name)    # Buddy
20print(Dog.species)  # Canis familiaris
21
22# Call methods
23print(dog1.bark())  # Buddy says Woof!

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In