class
In Python, the class
keyword lets you create user-defined classes, which are the cornerstone of object-oriented programming (OOP). With class
, you can define the blueprint for objects, complete with attributes (data) and methods (functions).
Python class
Keyword Examples
Here’s an example of how to define and use a class in Python:
>>> class Dog:
... def __init__(self, name):
... self.name = name
... def speak(self):
... return f"{self.name} says woof!"
...
>>> dog = Dog("Frieda")
>>> dog.speak()
'Frieda says woof!'
In this example, we define a Dog
class with an initializer method .__init__()
to set the dog’s name. The .speak()
method is an example of a behavior that objects of the Dog
class can perform. Then, you create an instance of the Dog
class named dog
and call its .speak()
method to see the output.
Related Resources
Tutorial
Python Classes: The Power of Object-Oriented Programming
In this tutorial, you'll learn how to create and use full-featured classes in your Python code. Classes provide a great way to solve complex programming problems by approaching them through models that represent real-world objects.
For additional information on related topics, take a look at the following resources:
- Object-Oriented Programming (OOP) in Python (Tutorial)
- Inheritance and Composition: A Python OOP Guide (Tutorial)
- Python Class Constructors: Control Your Object Instantiation (Tutorial)
- Class Concepts: Object-Oriented Programming in Python (Course)
- Inheritance and Internals: Object-Oriented Programming in Python (Course)
- Python Classes - The Power of Object-Oriented Programming (Quiz)
- Intro to Object-Oriented Programming (OOP) in Python (Course)
- Object-Oriented Programming (OOP) in Python (Quiz)
- Inheritance and Composition: A Python OOP Guide (Course)
- Inheritance and Composition: A Python OOP Guide (Quiz)
- Using Python Class Constructors (Course)
- Python Class Constructors: Control Your Object Instantiation (Quiz)