Another concept within
OOP
is the concept of polymorphism,
which basically translates to same action but different behavior.
The thing about polymorphism is that it's going to allow classes
to have methods with the exact same name
but then behave differently.
So as an example, still dealing with the user class,
we can have different types of users logging in both in a different manner.
So as an example, let's have different roles.
So I'm going to create a class for the regular user
and then a class for the admin user
and then they're gonna have unique ways of actually logging in. So
check this out. I'm gonna come in here right now and create class regular
user.
OK?
And now
I am going to define
very simply
the
method log in
and self.
OK. Notice I haven't passed in any attributes whatsoever.
I'm just going straight to the method. OK? So
what I'll do right now is
I am simply going to say print.
Now,
I would just say a regular user has logged
in.
OK?
Now look at this, OK? I'm gonna create another class
and let's call this the admin
user.
OK? Hold on.
And now again, define
and now the exact same method log in
self.
But now
it's gonna be a different print message
because now I'm gonna say admin has logged in
and let me just close this
and there it is. So now for the actual polymorphism, we're gonna make use of it.
Let's assign user
to be equal to regular user. So let's create our first objects in here for
the regular user.
Let's also create an object for the admin user.
And of course, I'll call this one admin equals to
admin
user.
And
it is so we've created objects for the regular user and the admin user,
let's now call them. So I'm gonna say user
dot log in
brackets and now
also admin dot log in
and there you go. So now let us try to run the program
and there it is
regular user has logged in,
admin has logged in.
So this is the concept of polymorphism where you can have two different classes
with the exact same method.
But that method will act in a different manner depending on which particular
object or class object is calling that method.
The method used here obviously is the login method.
It's applicable to both the class regular user
and the class admin user.
But it's gonna behave differently because it,
it's gonna print out a different message
depending on which class object actually logged in.
So that's polymorphism for you. Same action, different behavior.
Thank you for watching the video. I'll see you in the next class.