Expanding the User Class with Instance Methods
Understand what instance methods are.
Until now, we’ve had users post chirps manually by creating Post
objects and passing the user as an argument. But as our project grows, we begin to realize that it would be far more efficient and intuitive if users could create posts directly without having to construct Post
objects manually every time.
Why is this a problem?
In our current design, users must know how to create a Post
object, which isn’t very user-friendly or scalable. As we add more features (like liking posts or engaging with comments), this manual process becomes even more cumbersome. Wouldn’t it be much better if a user could simply call a method like create_post()
and have everything set up automatically?
This is where the relationship between a class and its objects becomes essential. A class is like a blueprint—it defines the structure and behavior (methods) that all its objects (instances) will have. When you create an object from a class, it inherits all the defined behaviors and properties. In object-oriented programming, methods are functions defined within a class that act on the object’s data using the self
parameter. By tying functionality like create_post()
to the User
class as an instance method, we enable each user object to “do something” on its own—such as creating posts or liking posts—without needing to manually assemble Post
objects outside of the user’s context. This design not only simplifies our code but also reinforces the core OOP principle that an object is a bundle of data and behavior.
Now, we’ll enhance our User
class by adding instance methods that let a user create posts and even like posts directly. This change streamlines our code and reinforces the natural connection between an object and the actions it can perform.
Why instance methods?
Before we dive into the implementation, ask yourself:
How do you usually tell an object to do something?
In our project, a user should be able to create a post without having to manually call the Post
class every time. Instance methods let us do just that!
Instance methods are functions that are defined inside a class and are called on objects. They have access to the instance’s data via the
self
parameter.
Adding create_post()
to the user class
We’ll add a create_post()
method inside our User
class. This method will construct a new Post
object automatically, linking the post to the user who created it. But before creating it, let’s visualize how it actually works.
Get hands-on with 1400+ tech skills courses.