Define a custom class with the class statement and instantiate it.
How It Works
The class statement creates a new type. Methods inside the class are functions that receive the instance through the first parameter by convention named self. Instances are constructed by calling the class.
Use meaningful class names and keep related behavior together.
Step-by-Step Example
class Greeting:
def say_hello(self, person_name):
return f"Hello, {person_name}!"
greeting = Greeting()
print(greeting.say_hello("Jordan"))
Understanding the Example
- The class groups related state and methods so each instance can manage its own values.
- The function definition gives the operation a reusable name and makes its inputs explicit.
A successful run of this example prints the following output:
Hello, Jordan!
Where This Fits in a Real Program
A class is useful when data and the operations that preserve its rules belong together. Distinguish class-level attributes from per-instance state, and make invalid operations fail clearly. Inheritance is not always needed: simpler composition or a standalone function may be easier to maintain.
Practice: Try It Yourself
Create a Timer class with a method that describes its configured duration.
For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.
Further Reading
Read the official Python documentation for complete parameters, return types and exceptions.
Common Beginner Mistakes
- Trying to call an instance method without supplying an instance through normal binding.
- Forgetting self in an instance method definition and getting an argument-count error.
Key Takeaways
- Define a custom class with the class statement and instantiate it.
- The class statement creates a new type.
- Use meaningful class names and keep related behavior together.