Classes help you group related data and actions together. They let you create your own types to organize code better.
Class definition syntax in Python
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Python
class ClassName: def __init__(self, parameters): # initialize attributes def method_name(self, parameters): # method actions
The class keyword starts the class definition.
The __init__ method sets up the object when created.
Examples
Dog with a name and a bark method.Python
class Dog: def __init__(self, name): self.name = name def bark(self): print(f"{self.name} says Woof!")
Car stores brand and year, and shows info.Python
class Car: def __init__(self, brand, year): self.brand = brand self.year = year def info(self): print(f"{self.brand} made in {self.year}")
Sample Program
This program defines a Person class with name and age. It creates a person named Alice and calls the greet method to say hello.
Python
class Person: def __init__(self, name, age): self.name = name self.age = age def greet(self): print(f"Hello, my name is {self.name} and I am {self.age} years old.") p = Person("Alice", 30) p.greet()
Important Notes
Always use self as the first parameter in methods to access object data.
Indentation is important to group code inside the class.
Class names usually start with a capital letter by convention.
Summary
Classes group data and functions to model real-world things.
Use class keyword and define an __init__ method to set up objects.
Methods inside classes use self to access object data.
Practice
1. What keyword is used to define a class in Python?
easy
Solution
Step 1: Identify the keyword for class definition
In Python, the keywordclassis used to start a class definition.Step 2: Differentiate from function and other keywords
defdefines functions,functionandobjectare not Python keywords for class definition.Final Answer:
class -> Option BQuick Check:
Class keyword = class [OK]
Hint: Remember: classes start with 'class' keyword [OK]
Common Mistakes:
- Using def instead of class
- Confusing function keyword with class
- Trying to use object keyword
2. Which of the following is the correct syntax to define a class named
Car?easy
Solution
Step 1: Check class header syntax
Python allows defining a class with or without parentheses if no base class is specified. Soclass Car:is correct.Step 2: Identify incorrect options
def Car():defines a function, not a class.class Car()is valid syntax but less common; however, it requires a colon at the end.class Car[]:is invalid syntax.Final Answer:
class Car: -> Option AQuick Check:
Class header ends with colon, no brackets [OK]
Hint: Class header ends with colon, no brackets needed [OK]
Common Mistakes:
- Using def instead of class
- Adding square brackets [] in class header
- Omitting colon at end
3. What will be the output of this code?
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
return f"{self.name} says Woof!"
my_dog = Dog("Buddy")
print(my_dog.bark())medium
Solution
Step 1: Understand the __init__ method
The__init__method setsself.nameto "Buddy" whenmy_dogis created.Step 2: Analyze the bark method output
Thebarkmethod returns a string usingself.name, so it returns "Buddy says Woof!".Final Answer:
Buddy says Woof! -> Option CQuick Check:
Method uses self.name = Buddy [OK]
Hint: Methods use self to access object data [OK]
Common Mistakes:
- Ignoring self and expecting just 'Woof!'
- Confusing class name with instance name
- Forgetting to pass name argument
4. Find the error in this class definition:
class Person:
def __init__(name):
self.name = name
p = Person("Alice")medium
Solution
Step 1: Check __init__ method parameters
The first parameter of instance methods must beself. Here,__init__lacksself.Step 2: Confirm other syntax correctness
Class header has colon, object creation syntax is correct, andself.nameassignment is proper.Final Answer:
Missing self parameter in __init__ method -> Option DQuick Check:
Instance methods need self as first parameter [OK]
Hint: Always include self as first method parameter [OK]
Common Mistakes:
- Omitting self in methods
- Forgetting colon after class name
- Misusing self in attribute assignment
5. You want to create a class
Book that stores title and author. Which is the best way to define the __init__ method to set these attributes?hard
Solution
Step 1: Define __init__ with self and parameters
The method must haveselfas first parameter, thentitleandauthorto receive values.Step 2: Assign parameters to object attributes
Useself.title = titleandself.author = authorto store values in the object.Final Answer:
def __init__(self, title, author): self.title = title self.author = author -> Option AQuick Check:
Init method sets attributes using self [OK]
Hint: Use self.param = param to store values in __init__ [OK]
Common Mistakes:
- Omitting self parameter
- Assigning attributes backwards
- Not passing parameters to __init__
