Ready to Dive into Object-Oriented Programming?
Python Classes and Objects: An Essential Introduction
The fundamentals of Python classes and objects.
Ever wondered about Object-Oriented Programming (OOP)? You’ve likely heard of the ‘class’ keyword but haven’t delved into using it. Now’s the time to demystify OOP and harness its power in Python.
In this article, I will take you through an exploration of Python’s string objects as a gateway to understanding broader concepts like classes, objects and instances. We will start by examining a simple string to uncover the wealth of methods available under Python’s hood, revealing how these methods can be utilized to manipulate and process data effectively. Further, we will define key terms such as class, object, instance and instantiation and distinguish between classes and objects. Finally, I will guide you through creating a user-defined object, setting the stage for more advanced programming techniques. Join me in unraveling these foundational concepts, which are crucial for mastering Python and enhancing your coding toolkit.
As someone who is passionate about Python and its capabilities, I post regularly about different aspects of Python programming, ranging from beginner tips to advanced techniques. By following my articles, you can stay updated with the latest Python trends, enhance your coding skills and discover new ways to apply Python in your projects. Additionally, I would greatly appreciate it if you could drop a clap and follow, as your support motivates me to create more valuable content. Together, we can navigate the fascinating world of Python and unlock its full potential.
Please consider Follow me to keep up with the latest articles and continue expanding your programming knowledge.
Introduction
In the world of Python programming, you frequently interact with various built-in objects and strings are one of the most fundamental among them. Consider the simple line of code: s = "I am a string". When you query the type of s using print(type(s)), Python identifies s as an instance of the str class, which encapsulates the concept of a string. This moment of interaction with s opens a window into the profound architecture of Python, where even a seemingly simple string is an object derived from a class with rich functionality.
To further explore this, if you add print(dir(str)) to your script and execute it, you will receive a list detailing the myriad attributes and methods associated with the string class. This output might initially seem overwhelming, but it includes familiar operations like upper() and lower(), which hint at the inherent capabilities of string objects. These methods are just the beginning of what string objects can do, demonstrating that strings are not just mere collections of characters but are powerful tools for data collection and manipulation.
The String Object
You have already been using built-in Python objects. Strings are an example of a Python object.
s = "I am a string"
print(type(s))
Python says that the type of s is the class str (which is a string). Add the following line of code and run the program again.
print(dir(str))dir is a built-in function that reveals all the attributes and methods linked to a class. The output may initially appear overwhelming, but some elements, such as upper and lower, might be recognizable. While attributes and methods will be explored in more detail in a future lesson, it's crucial to recognize that a string is more than just a sequence of characters. As a class, a string serves as an effective tool for gathering and altering data.
What will occur if you:
- Insert the line of code
print(s.__add__("!"))? - Insert the line of code
print(s.__sizeof__())? - Insert the line of code
print(s.startswith("I"))?
# In Python, strings are objects and "s" is an instance of the str class.
s = "I am a string"
# print(dir(str))
# The __add__ method is used to concatenate strings.
# Here it's used to add an exclamation mark to the string s.
print(s.__add__("!")) # Output: I am a string!
# The __sizeof__ method returns the size of the object in memory, in bytes.
print(s.__sizeof__()) # This output may vary depending on the system.
# The startswith method checks if the string starts with the specified substring.
print(s.startswith("I")) # Output: True because s starts with "I".Your engagement, whether through claps, comments, or following me, helps me creating and sharing more informative content.
Vocabulary
The terms “class” and “object” might seem to be used interchangeably. While there are several similarities between classes and objects, there are crucial differences to note. Additionally, working with objects involves a distinct set of specialized terminology.
Classes
Classes represent a structured combination of data and the functions that can manipulate this data. Programming, being an inherently abstract activity, benefits greatly from classes, which provide a conceptual model to help users think about data more concretely. Serving as blueprints, classes outline to Python not only what data to collect but also how this data can be altered.
Objects
Objects are created based on the blueprint provided by a class. For example, in the code mentioned earlier, the variable s is an instance of a string object, not the class itself. The string class informs Python that s possesses methods such as __add__, __sizeof__ and startswith. Thus, when a programmer intends to utilize the functionality defined in a class, they instantiate an object.
Instance
Another common terminology programmers use when discussing objects is to describe an object as an “instance” of a particular class. This means that the object is a specific realization of the class, embodying all the characteristics and behaviors defined in that class. For instance, the variable s in our previous example is an instance of the string class. This indicates that s not only contains data structured according to the string class but also inherits all the methods and properties defined by the string class, allowing it to behave as a string in the program.
Instantiation
Instantiation is the process where an object is created according to blueprint of the class. The phrase “define a variable” means to create a variable. The variable is given a name and a value. Once it has been defined, you can use the variable. With objects, you use the phrase “instantiate an object”. That means to create an object, give it a name, store any data and define the actions the object can perform.
Enough theory! Let’s dive into how you can define your own objects and create custom instances in Python.
User-Defined Object
Defining an Object Assume you want to collect information about actors. Creating a class is a good way to keep this data organized. The class keyword is used to define a class. For now, use pass as the body of the class. Declaring a class does not doing anything on its own, so print Actor.
class Actor:
pass
print(Actor)Naming classes
The convention for naming classes in Python is to use a capital letter. A lowercase letter will not cause an error message, but it is not considered to be “correct”. If a class has a name with multiple words, do not use an _ to separate the words like for variable and function names. Instead, all of the words are pushed together and a capital letter is used for the first letter of each word. This is called camel case.
Get CyCoderX’s stories in your inbox
Join Medium for free to get updates from this writer.
Classes are just the blueprint. To you use a class, you need to instantiate an object. Here is an object to represent the actor, John.
class Actor:
pass
john= Actor()
print(type(helen)So you now have John, which is an instance of the Actor class.
Adding Attributes
The purpose of having a class is to gather information and define actions that can modify that data. For instance, an Actor class should include details such as the actor’s name, notable films, awards they have won and so on. These pieces of information associated with a class are known as attributes. Attributes are accessed using dot notation, which follows the format object_name.attribute. You can add an attribute using the assignment operator, like this: object_name.attribute = attribute_value. Object attributes can be used just like any other variable.
class Actor:
''' Define the actor class '''
pass
john = Actor()
john.first_name = "John"
john.last_name = "Smith"
print(john.first_name, john.last_name)
helen = Actor()
helen.first_name = "Helen"
helen.last_name = "Mirren"
helen.birthday = "July 26"
helen.total_films = 80
helen.oscar_nominations = 4
helen.oscar_wins = 1
print(helen.first_name, helen.last_name)
Too much code
Consider the Actor class, which we’ve defined previously. By creating instances of this class, such as for actors John and Helen, we can assign attributes to each actor. For example, we can specify John’s first and last names as “John” and “Smith” respectively and then print these values. Similarly, we can define Helen’s details including her first name, last name, birthday, total number of films, Oscar nominations and Oscar wins and print her first and last names as well.
However, adding each attribute one by one for each actor can result in a lot of repetitive code. This method is not only time-consuming but also inefficient, especially as the number of attributes increases or when you need to create many instances. To address this issue, using a constructor in the Actor class can help streamline the process of initializing objects with their respective attributes in a more concise and organized manner.
Interested in learning more about Data Engineering and Cloud Computing? Click here to read my Medium article on using the dotenv module for secure configurations.
The Constructor
The class Actor does nothing but create a class. It does not create any attributes; the user has to do this. A class is suppose to be a blueprint. It should lay out all of the attributes for the user. Classes can do this when you use the constructor.
A constructor is a special method within a class (we will cover methods in more detail in a later lesson). Its primary role is to initialize all the attributes associated with an object. These attributes are known as instance variables. In Python, the constructor method is written as __init__. The double underscores before and after init are mandatory. The constructor must also include self as a parameter. The syntax for the constructor is similar to that of a function and it needs to be indented by four spaces to indicate that it is part of the class. Attributes are accessed using self.attribute_name. When you create an instance of the Actor class, such as helen, the constructor is automatically called, setting up the initial state of the object.
What’s the deal with the double underscores? In Python, methods with double underscores are commonly found in objects and are known as “dunder” methods. These methods are implicit, meaning they operate behind the scenes in response to explicit actions. For example, you never need to explicitly call helen.__init__. When you create an instance of the class, Python automatically invokes the __init__ method to initialize the object. This implicit mechanism helps streamline the coding process by handling routine tasks automatically.
class Actor:
"""Define the actor class"""
def __init__(self, first_name, last_name, birthday, total_films, oscar_nominations, oscar_wins):
self.first_name = first_name
self.last_name = last_name
self.birthday = birthday
self.total_films = total_films
self.oscar_nominations = oscar_nominations
self.oscar_wins = oscar_wins
john = Actor("John", "Smith", "June 20", 80, 4, 1)
tom = Actor("Tom", "Hanks", "July 9", 76, 5, 2)
print(john.first_name, john.last_name)
print(tom.first_name, tom.last_name)Conclusion
In conclusion, understanding Python classes and objects is fundamental to mastering object-oriented programming in Python. Classes serve as blueprints for creating objects, encapsulating data and defining the methods that can manipulate this data. By utilizing classes and objects, you can organize your code more efficiently, making it more modular, readable and easier to maintain. This article has introduced you to the basic concepts of classes, objects and constructors, highlighting how they work together to form the backbone of Python’s object-oriented capabilities.
As you continue your journey in Python programming, remember that these foundational concepts will be instrumental in tackling more complex projects and applications. From web development to data analysis and machine learning, the principles of object-oriented programming will enable you to build robust and scalable software solutions. Keep exploring, practicing and applying these concepts to real-world problems and you’ll unlock the full potential of Python in your coding endeavors. Follow my articles to stay updated with advanced techniques and new insights that will further enhance your programming skills.
Final Words:
Thank you for taking the time to read my article.
This article was first published on medium by CyCoderX.
Hey There! I’m CyCoderX, a data engineer who loves crafting end-to-end solutions. I write articles about Python, SQL, AI, Data Engineering, lifestyle and more!
Join me as we explore the exciting world of tech, data and beyond!
For similar articles and updates, feel free to explore my Medium profile
If you enjoyed this article, consider following for future updates.
Interested in Python content and tips? Click here to check out my list on Medium.
Interested in more SQL, Databases and Data Engineering content? Click here to find out more!
What did you think about this article? Let me know in the comments below … or above, depending on your device 🙃










