Python is an object-oriented programming language, with objects (concepts) belonging to a class. Classes can be defined by the user, complete with class objects, class attributes, and methods. It all starts when you give your class a name, then you define the different parts of your class.
In Python, classes can be extremely simple or complex, depending on what you need them to do.
How to Define a Class in Python
First, give your class a name:
Next, define the attributes and methods you’d expect objects in this class to possess:
color = ‘brown’
shape = ‘sliced’
print(‘Into the void.’)
As you can see, the class Bread has the attributes of brown color and sliced shape. It also has the methods butter and eaten, which print the associated messages. The self parameter on the class instance-methods does not affect functions that are called from outside the class.
Instantiating Objects of Python Classes
We can now define an instance of the class Bread. Let’s create a new instance using the class:
sourdough = Bread()
This means the instance sourdough has all of the attributes and methods of the class Bread. We can now add additional attributes to the object sourdough.
sourdough = Bread()
sourdough.taste = ‘sour’
Now, sourdough is brown, sliced, can be buttered, can be eaten, and has a sour taste.
When to Use Classes You Define in Python
Since Python is an object-oriented language, you’ll be using user-defined classes a lot. Classes are powerful tools for working effectively with data and functionality to engineer software that can be used by you and other developers. They can also be incredibly fun and versatile.
Take Your Python Skills to the Next Level with Hackbright
Python is a versatile and beginner-friendly programming language, and Hackbright is a coding bootcamp with a supportive community and Python-centered curriculum. If you want to learn Python and are looking for more structure, check out our 12-week Software Engineering course.
What Is the Python Interpreter?
What Can I Do with Python? Tips and Tricks
- Admissions Office (28)
- Adora Cheung (5)
- Alum (98)
- Blog (168)
- Career Services (26)
- Diversity (18)
- Engineering Advice (67)
- Hackbright Field Trips (24)
- Hackbright Mentors (21)
- Hackbright News (109)
- Homejoy (5)
- Podcast (2)
- Profiles of Engineers (110)
- Recruiting & Hiring (16)
- Resources (47)
- Student Blogs (24)
- Tech (54)
- Thought Piece (23)
- Uncategorized (61)
- Video (20)