Introduction
Much like how functions make our code more reusable by abstracting away code, objects help us to do the same thing.
This post will focus on classes--the means to create an object and a central part of Object-Oriented Programming (OOP).
Classes
Very similar to a function, classes help us organize our code slightly more efficiently.
If you've read my posts on C, you'll find that classes are, indeed, very similar to structs: They consolidate multiple fields of data into one custom data structure.
Suppose we want to create a program to keep track of a couple of our phone contacts.
Consider this program:
def main():
contact1 = "Name: Alicent, Age: 37, Email: alicenth@gmail.com"
contact2 = "Name: Helaena, Age: 20, Email: helaenat@gmail.com"
main()
It doesn't do much, but notice the inefficiency here in allotting different fields of data to a single string--one slight mistype to a string can create an inconsistency.
Instead, classes allow us to merge different variables into one "super variable" or class.
Here, we might try to separate this large contact string into different variable fields for "name," "age," and "email:"
class Contact:
def __init__(self, name, age, email):
self.name = name
self.age = age
self.email = email
Notice how:
we create a class using the class keyword
the name "Contact" is capitalized by convention
there is a function, __init__ that takes "self" as well as our desired fields as arguments
self refers to the individual object that is created when we create an object of this class
we assign those attributes of the objects to the parameters passed to the function
Now, we can replace our old code with a class in action:
class Contact:
def __init__(self, name, age, email):
self.name = name
self.age = age
self.email = email
def main():
contact1 = Contact(name="Alicent", age=37, email="alicent@gmail.com")
contact2 = Contact(name="Helaena", age=20, email="helaena@gmail.com")
main()
Notice how:
we did not include an argument for self
we instantiated this class "Contact" to create a Contact object by called Contact( )
unlike normal Python functions, classes require you to specify the field name and assign it a value
Final Thoughts
Now, we have a much, much better way to store data for a contact than just through a flimsy string.
Thanks for reading!
Comments