The class Keyword and Base Code Block Syntax
π·οΈ Object-Oriented Programming (OOP) Basics / Defining a Class
Welcome to the world of Object-Oriented Programming! If you have been writing Python scripts that are mostly linearβrunning from top to bottomβyou are about to learn a powerful way to organize your code. A class is like a blueprint. Instead of writing the same logic over and over, you define a class once, and then create multiple instances (objects) from it. This makes your code cleaner, reusable, and much easier to maintain as your projects grow.
βοΈ What is a Class?
Think of a class as a cookie cutter. The cutter itself is the classβit defines the shape. The actual cookies you bake are the objects (or instances). Each cookie can have its own sprinkles (data), but they all share the same basic shape (behavior).
- Class: The blueprint or template.
- Object: A specific item created from that blueprint.
- Attributes: Variables that belong to the class (data).
- Methods: Functions that belong to the class (actions).
π οΈ The class Keyword
To create a class, you use the class keyword, followed by the name of your class and a colon. Class names are typically written in PascalCase (each word starts with a capital letter, no underscores).
- Syntax:
class ClassName: - The code block that follows must be indented (usually 4 spaces).
- Inside this block, you define all the attributes and methods for the class.
π Base Code Block Syntax
Here is the simplest possible class structure. It does nothing yet, but it shows the correct syntax:
- Start with
class MyClass: - On the next line, indented by 4 spaces, write
pass(a placeholder that means "do nothing").
This is a valid, complete class. You can create objects from it, but it won't have any custom behavior yet.
π΅οΈ Breaking Down the Structure
Let's look at a slightly more useful example to see how the pieces fit together:
class Car:β This declares a new class named Car.def __init__(self, brand, color):β This is a special method called the constructor. It runs automatically when you create a new object. Theselfparameter refers to the specific object being created.self.brand = brandβ This stores the brand value inside the object.self.color = colorβ This stores the color value inside the object.def honk(self):β This is a regular method. It also takesselfas its first argument so it can access the object's data.return f"{self.brand} says Beep Beep!"β This method returns a string using the object's own brand attribute.
π Comparison: Function vs. Class
| Feature | Regular Function | Class with Methods |
|---|---|---|
| Purpose | Performs a single task | Groups data + behavior together |
| Reusability | You call the function | You create multiple objects from the class |
| Data storage | Variables are temporary (local) | Data persists inside each object |
| Organization | Flat, linear | Structured, hierarchical |
| Example | def greet(name): |
class Person: def __init__(self, name): |
π§ͺ Creating an Object from a Class
Once you have defined a class, you create an object by "calling" the class like a function:
my_car = Car("Toyota", "Red")β This creates a new Car object. The arguments "Toyota" and "Red" are passed to the__init__method.print(my_car.brand)β This accesses the brand attribute of the object. Output: Toyotaprint(my_car.honk())β This calls the honk method. Output: Toyota says Beep Beep!
Each object is independent. You could create a second car: your_car = Car("Honda", "Blue"). Changing your_car does not affect my_car.
β Key Takeaways
- Use the
classkeyword to define a blueprint for objects. - The class body is indented; use
passas a placeholder if needed. - The
__init__method initializes each new object's data. - The
selfparameter is always the first parameter in methodsβit refers to the current object. - Create objects by calling the class like a function:
object_name = ClassName(arguments). - Classes help you write code that is organized, reusable, and mirrors real-world concepts.
Now you are ready to start building your own blueprints. Next, you will learn how to add more methods and attributes to make your classes truly powerful!
The class keyword creates a blueprint for objects, and the code block inside defines what data and behaviors those objects will have.
π’ Example 1: Simplest possible class with no content
This example shows the most basic class structure β an empty blueprint.
class EmptyClass:
pass
π€ Output: No output (class defined but not used)
π΅ Example 2: Class with a single attribute
This example shows how to assign a fixed value inside a class.
class Car:
color = "red"
π€ Output: No output (class defined but not used)
π‘ Example 3: Creating an object from a class
This example shows how to use a class to build an actual object.
class Dog:
breed = "labrador"
my_dog = Dog()
print(my_dog.breed)
π€ Output: labrador
π Example 4: Class with a method (function inside a class)
This example shows how to add behavior to a class using a method.
class Calculator:
def add(self, a, b):
result = a + b
return result
calc = Calculator()
output = calc.add(3, 5)
print(output)
π€ Output: 8
π΄ Example 5: Class with multiple attributes and methods
This example shows a practical class that stores data and performs actions.
class Employee:
company = "TechCorp"
def set_name(self, first, last):
self.first_name = first
self.last_name = last
def full_name(self):
name = self.first_name + " " + self.last_name
return name
engineer = Employee()
engineer.set_name("Ana", "Chen")
print(engineer.company)
print(engineer.full_name())
π€ Output: TechCorp
Ana Chen
π Comparison Table: Class vs Object
| Feature | Class | Object |
|---|---|---|
| What it is | Blueprint or template | Actual thing created from the blueprint |
| Created with | class keyword |
Class name followed by parentheses () |
| Contains | Attributes and method definitions | Real data assigned to attributes |
| Example | class Car: |
my_car = Car() |
| Can be used directly? | No, must create an object first | Yes, after creation |
Welcome to the world of Object-Oriented Programming! If you have been writing Python scripts that are mostly linearβrunning from top to bottomβyou are about to learn a powerful way to organize your code. A class is like a blueprint. Instead of writing the same logic over and over, you define a class once, and then create multiple instances (objects) from it. This makes your code cleaner, reusable, and much easier to maintain as your projects grow.
βοΈ What is a Class?
Think of a class as a cookie cutter. The cutter itself is the classβit defines the shape. The actual cookies you bake are the objects (or instances). Each cookie can have its own sprinkles (data), but they all share the same basic shape (behavior).
- Class: The blueprint or template.
- Object: A specific item created from that blueprint.
- Attributes: Variables that belong to the class (data).
- Methods: Functions that belong to the class (actions).
π οΈ The class Keyword
To create a class, you use the class keyword, followed by the name of your class and a colon. Class names are typically written in PascalCase (each word starts with a capital letter, no underscores).
- Syntax:
class ClassName: - The code block that follows must be indented (usually 4 spaces).
- Inside this block, you define all the attributes and methods for the class.
π Base Code Block Syntax
Here is the simplest possible class structure. It does nothing yet, but it shows the correct syntax:
- Start with
class MyClass: - On the next line, indented by 4 spaces, write
pass(a placeholder that means "do nothing").
This is a valid, complete class. You can create objects from it, but it won't have any custom behavior yet.
π΅οΈ Breaking Down the Structure
Let's look at a slightly more useful example to see how the pieces fit together:
class Car:β This declares a new class named Car.def __init__(self, brand, color):β This is a special method called the constructor. It runs automatically when you create a new object. Theselfparameter refers to the specific object being created.self.brand = brandβ This stores the brand value inside the object.self.color = colorβ This stores the color value inside the object.def honk(self):β This is a regular method. It also takesselfas its first argument so it can access the object's data.return f"{self.brand} says Beep Beep!"β This method returns a string using the object's own brand attribute.
π Comparison: Function vs. Class
| Feature | Regular Function | Class with Methods |
|---|---|---|
| Purpose | Performs a single task | Groups data + behavior together |
| Reusability | You call the function | You create multiple objects from the class |
| Data storage | Variables are temporary (local) | Data persists inside each object |
| Organization | Flat, linear | Structured, hierarchical |
| Example | def greet(name): |
class Person: def __init__(self, name): |
π§ͺ Creating an Object from a Class
Once you have defined a class, you create an object by "calling" the class like a function:
my_car = Car("Toyota", "Red")β This creates a new Car object. The arguments "Toyota" and "Red" are passed to the__init__method.print(my_car.brand)β This accesses the brand attribute of the object. Output: Toyotaprint(my_car.honk())β This calls the honk method. Output: Toyota says Beep Beep!
Each object is independent. You could create a second car: your_car = Car("Honda", "Blue"). Changing your_car does not affect my_car.
β Key Takeaways
- Use the
classkeyword to define a blueprint for objects. - The class body is indented; use
passas a placeholder if needed. - The
__init__method initializes each new object's data. - The
selfparameter is always the first parameter in methodsβit refers to the current object. - Create objects by calling the class like a function:
object_name = ClassName(arguments). - Classes help you write code that is organized, reusable, and mirrors real-world concepts.
Now you are ready to start building your own blueprints. Next, you will learn how to add more methods and attributes to make your classes truly powerful!
Interactive Views
You are currently in π All-in-One mode. Use the tabs at the top to switch to π Theory Only or π» Code Only views.
The class keyword creates a blueprint for objects, and the code block inside defines what data and behaviors those objects will have.
π’ Example 1: Simplest possible class with no content
This example shows the most basic class structure β an empty blueprint.
class EmptyClass:
pass
π€ Output: No output (class defined but not used)
π΅ Example 2: Class with a single attribute
This example shows how to assign a fixed value inside a class.
class Car:
color = "red"
π€ Output: No output (class defined but not used)
π‘ Example 3: Creating an object from a class
This example shows how to use a class to build an actual object.
class Dog:
breed = "labrador"
my_dog = Dog()
print(my_dog.breed)
π€ Output: labrador
π Example 4: Class with a method (function inside a class)
This example shows how to add behavior to a class using a method.
class Calculator:
def add(self, a, b):
result = a + b
return result
calc = Calculator()
output = calc.add(3, 5)
print(output)
π€ Output: 8
π΄ Example 5: Class with multiple attributes and methods
This example shows a practical class that stores data and performs actions.
class Employee:
company = "TechCorp"
def set_name(self, first, last):
self.first_name = first
self.last_name = last
def full_name(self):
name = self.first_name + " " + self.last_name
return name
engineer = Employee()
engineer.set_name("Ana", "Chen")
print(engineer.company)
print(engineer.full_name())
π€ Output: TechCorp
Ana Chen
π Comparison Table: Class vs Object
| Feature | Class | Object |
|---|---|---|
| What it is | Blueprint or template | Actual thing created from the blueprint |
| Created with | class keyword |
Class name followed by parentheses () |
| Contains | Attributes and method definitions | Real data assigned to attributes |
| Example | class Car: |
my_car = Car() |
| Can be used directly? | No, must create an object first | Yes, after creation |