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.
- Admissions Office (13)
- Adora Cheung (1)
- Alum (84)
- Blog (135)
- Career Services (22)
- Data Science and Business Intelligence (1)
- Diversity (12)
- Engineering Advice (62)
- Hackbright Field Trips (19)
- Hackbright Mentors (20)
- Hackbright News (64)
- Homejoy (1)
- Podcast (1)
- Profiles of Engineers (96)
- Recruiting & Hiring (15)
- Resources (38)
- Student Blogs (22)
- Tech (45)
- Thought Piece (22)
- Uncategorized (44)
- Video (13)