Before you write your custom Ingredient class, take a moment to consider what a class in Python is.
What is a Python Class
So, a class defines what an object instance of that class will look like.
Info: A class is a blueprint for an object.
But that just brings up another question: What is an object?
Python Objects
You might remember reading some variation of the following sentence earlier in this course or somewhere else on the Internet:
Everything in Python is an object.
You might have accepted this sentence as an axiom or brushed it aside as an irrelevant detail. Now is the time when you'll dig a little deeper to find out what this really means.
In the previous modules of this course, you've encountered all sorts of different data types in Python. You've used the int type to make calculations, the str type to communicate with your users, and the list and dict types to store and access information. You've also written functions to group logic and reuse code logic.
Now, here is a little sentence that tries to tell you that all that different stuff you've encountered is really the same at its base:
Everything in Python is an object.
That's right! An int is an object, a str is an object, a list is, and a dict is an object as well. Even a function is an object in Python! Everything.
Custom Objects
And here comes the exciting part. Python is modular, and even the basic data types are just objects, which means that you can create your own data types:
class Ingredient:
"""Creates an empty Ingredient object."""
pass
i = Ingredient() # Instantiating an object of the class
print(type(i)) # OUTPUT: <class '__main__.Ingredient'>
In the code snippet above, you created a custom class Ingredient. You didn't define any attributes or methods for the class, so it currently doesn't do anything and isn't anything special, either. But it's still its own custom class! You proved that by creating an object of the Ingredient class:
i = Ingredient()
Then, you printed the type() of this new object of your custom class that you instantiated. The result shows you that Python considers this object as part of the custom Ingredient class that you've created above:
# OUTPUT:
<class '__main__.Ingredient'>
User-defined types are called classes. You have seen several examples of classes before without really needing to know what they are. You've seen built-in types, such as int or str, and you've seen other classes, such as the Path object from the pathlib module. In the rest of this section, you'll learn to build your own classes.
Additional Resources
- effbot: Python Objects
Summary: Python Classes and Python Objects
- A class defines what its instance object will look like
- Classes are "blueprints" for Objects
- Everything in Python is an object (variables, functions, etc)
- Creating a class allows you to create custom objects
- A class is a user-defined type