Learn Python OOP in under 20 Minutes
Summary
TLDRIn this educational video, the concept of Python classes is explored through an analogy with blueprints for constructing a house. The class is introduced as a template for creating objects, with a focus on the 'microwave' class. Key elements such as class instantiation, initializers, and instance methods are covered. The video demonstrates how to define and use methods within a class, like 'turn on' and 'run', to simulate the functionality of a microwave. Additionally, the use of dunder methods for customizing operator behavior and string representations of classes is explained, highlighting the importance of classes in organizing code and enhancing functionality.
Takeaways
- ποΈ Classes in Python serve as blueprints for creating objects, defining their structure and behavior.
- π The class keyword in Python is used to define a class, and class names follow the camel case convention.
- π§ Instantiating a class creates an object, or an instance of that class, using the constructor (parentheses).
- β Type annotations are optional in Python and are used for code editor assistance, not for runtime functionality.
- π οΈ Initializers, or the __init__ method, allow customization of each instance with specific information.
- π The 'self' keyword in class methods refers to the instance of the class and ensures data sticks to the correct object.
- π Methods within a class define the functionality of the objects, such as turning a microwave on or off.
- π Dunder (double underscore) methods are special methods in Python classes that allow customization of built-in operations.
- π The __add__ method is an example of a dunder method that can be defined to handle the addition of two objects.
- π The __str__ and __repr__ dunder methods provide user-friendly and developer-friendly string representations of objects, respectively.
Q & A
What is a class in Python?
-A class in Python is a blueprint for creating objects. It defines the properties and methods that an object of that class will have.
Why are classes useful in Python programming?
-Classes are useful because they allow for the creation of custom objects with specific properties and behaviors, promoting code reusability and organization.
What is an instance in the context of classes?
-An instance is a specific object created from a class blueprint. It represents a unique object with its own set of attributes and behaviors as defined by the class.
How do you create a class in Python?
-In Python, you create a class by using the 'class' keyword followed by the class name and a colon. The class name should follow the camel case convention, starting with an uppercase letter.
What is the purpose of the __init__ method in a class?
-The __init__ method is a special method called a constructor in Python. It is used to initialize the attributes of a class when an object is created.
What does 'self' represent in a class method?
-'self' represents the instance of the class and is used to access variables and methods within the class. It ensures that the data and methods belong to the correct instance.
How can you add functionality to a class in Python?
-You can add functionality to a class by defining methods within the class. Methods are functions that belong to the class and can perform actions on the object's data.
What is a Dunder method in Python?
-A Dunder method, short for 'double underscore' method, is a special method in Python classes that starts and ends with double underscores. These methods have special meanings and are called 'magic methods'.
Why is the string representation of an object important?
-The string representation of an object is important because it provides a human-readable description of the object, which is useful for debugging and logging.
How can you customize the way an object is displayed when printed?
-You can customize the way an object is displayed when printed by defining the __str__ method in the class. This method should return a string that represents the object.
What is the difference between __str__ and __repr__ methods in Python classes?
-The __str__ method should return a user-friendly string representation of the object, while the __repr__ method should return a developer-friendly representation that could be used to recreate the object if possible.
Outlines
π Introduction to Python Classes
The video begins with an introduction to Python classes, explaining that a class acts as a blueprint for creating objects, similar to a house blueprint. The instructor uses the analogy of a microwave manufacturer to illustrate how classes can be used to design and create objects with specific attributes. The class is initially empty but can be used to instantiate objects, such as a microwave with the brand 'Smeg'. The video also touches on type annotations, which are helpful for code editors but not necessary for the code to function.
π§ Customizing Classes with Initializers
The second paragraph delves into customizing classes with initializers. The instructor demonstrates how to use the `__init__` method to create instances of a class with specific information, such as brand and power rating. This allows each microwave instance to have unique data. The concept of 'self' is introduced as a reference to the current instance of the class, ensuring that data sticks to the correct object. The paragraph also mentions the flexibility of renaming 'self' to other variable names, although it's not recommended due to Python conventions.
π Adding Functionality with Methods
In the third paragraph, the focus shifts to adding functionality to classes through methods. The instructor creates methods like 'turn_on' and 'turn_off' to manipulate the state of the microwave object, introducing a 'turned_on' attribute to track the microwave's state. A 'run' method is also added to simulate the microwave's cooking function. The video shows how these methods can be used to interact with the microwave objects, providing a practical demonstration of object-oriented programming in Python.
π Exploring Dunder Methods for Custom Operations
The final paragraph explores dunder (double underscore) methods, which allow for custom behavior when using operators with class instances. The instructor demonstrates how to define the addition operator to combine two microwave objects into a 'fusion' of their brands. Other dunder methods like `__mul__` for multiplication and `__str__` for string representation are discussed, showing how they can be customized to provide user-friendly or developer-oriented information. The video concludes with a summary of the benefits of using classes to organize code and the ease of reusing functionality across different instances.
Mindmap
Keywords
π‘Class
π‘Object
π‘Blueprint
π‘Camel Case
π‘Initializer
π‘Self
π‘Method
π‘Type Annotation
π‘Dunder Method
π‘Instance
Highlights
Classes in Python are introduced as blueprints for objects, similar to a house blueprint.
A class is defined using the 'class' keyword followed by the class name in camel case.
Instantiating a class creates an object, or instance, from the class blueprint.
Type annotations are mentioned as optional but useful for code editors.
Initializers, or constructors, are used to add specific information to instances.
The 'self' keyword is used to reference the instance within the class methods.
Methods are functions within a class that give the object functionality.
Demonstrates creating a 'turn on' method for the microwave class.
Shows how to create a 'turn off' method to complement the 'turn on' method.
Introduces a 'run' method to simulate the microwave cooking process.
Explains the concept of Dunder methods and their role in defining operations on objects.
Demonstrates defining the 'add' Dunder method to combine two microwave instances.
Covers the 'mul' Dunder method for multiplying instances, returning a custom string.
Discusses the 'str' Dunder method for user-friendly string representation of objects.
Differentiates between the 'str' and 'repper' Dunder methods for user and developer readability.
Concludes by emphasizing the organizational benefits of classes in Python for code functionality.
Transcripts
this video was brought to you by IND
dentle IO learning python Made Simple
how's it going everyone in today's video
we're going to be learning about classes
in Python what they are and how we can
use them but before we do anything I'm
just going to explain a bit of the
theory and to keep it simple a class is
just a blueprint for what an object
should look like and how it should
function for example before you build a
house usually you would create a
blueprint containing all the relevant
information and functionality regarding
how that house should look and how it
should function before you start
building it and classes are no different
they contain all the relevant
information for what an object should do
so for this lesson we're going to
pretend that we are a microwave
manufacturer which means first we're
going to design the blueprint and then
we're actually going to create the
microwaves using that blueprint now in
Python if you want to create a class you
use the class keyword followed by the
class name and the class name
conventionally should follow camel case
which means it will start with uppercase
and every additional word will also
start with uppercase so if you had a
class called blue car you'll see that
each time you have a new word it starts
with an uppercase character but in this
example we're going to call it microwave
and for now it's going to be empty but
already with this code we can start
creating objects from this class because
now we have the blueprint which means
that we can actually get started with
creating some microwaves so here what
we're going to do is instantiate a
microwave and to do that we're going to
create a variable called Smeg which is a
brand or a type of microwave you can
search it on Google it's a very nice
brand and that's going to be of type
microwave which will equal the
microwave with the Constructor which are
these parentheses once you use the
parenthesis on a class this creates an
instance of that class which means we're
creating a unique microwave from this
blueprint also it's worth mentioning you
did not have to include this bit here
this is what they refer to as a type
annotation or a type hint it's only used
for code editors so if you don't like
type annotations you can safely ignore
that in all my videos I use type
annotations because I find them very
useful and I will use them throughout
this lesson as well but it's up to you
whether you want to include type
annotations or not in your code anyway
now we have an instance of a microwave
which is called smag which means if we
were to print this what we're going to
get back is a unique ID pointing to the
unique instance of this microwave but as
it stands this class is kind of useless
it doesn't contain any useful
information nor functionality so next
we're going to modify it because we want
our microwaves to be be a bit more
customizable so next we're going to be
learning about initializers how to
create instance with specific
information which actually kind of
customizes each one of the microwaves
that we create so here we're going to be
using a Dunder method called init and by
default init returns none you're not
required to provide this I just like to
do it with all my code because it makes
it extra explicit the initializer takes
care of initializing the class which
means if you have any extra information
you want to give the class when you are
creating an instance that code is going
to be run here as soon as you
instantiate it so right after Self we're
going to type in brand of type string
and power rating of typ string and
inside here we need to type in self.
brand equals brand and self. power
rating equals power rating and
immediately we're going to get some
syntax highlighting because we need to
now provide this information
to the
Constructor so here we're going to give
it the brand of
Smeg and we're going to give it a power
rating of B and thanks to this
information we now have a microwave that
actually contains some data so if we
were to print sm. brand and sm. power
rating you'll see that this class will
contain that information it's going to
return to us the information that we
inserted and we can even create another
mic microwave which we're going to call
Bosch or
bch and that's going to equal this
microwave with the brand set to Bosch do
let me know in the comment section down
below how much I'm messing that up and
the power rating will be set to C then
we can print bch do brand and the power
rating and what we should get is the
information from Bosch now but right now
you're probably asking okay that makes
sense but what is self you completely
skipped self well self is the actual
instance of the class and that just
makes sure that all this data sticks to
the correct instance or to the correct
object in the case of smag as soon as we
insert this information self turns into
smag so all of these become smag but
that's only when we're referring to smag
otherwise if we're referring to bch
this becomes bch which means when we
call b. brand it gives us the correct
data back so again self just refers to
whichever instance we're currently using
and one thing that's quite cool that a
lot of beginners don't know about is
that you can actually change this name
to whatever you want you can even change
it to this which is something popular in
Java or you can change it to something
called
instance if that's what you want you can
do it I do not recommend you do that
because conventionally we will always
have this as self if you look at other
tutorials or you look at documentation
online this will always be referred to
as self but it's just a convention so if
you really want to change this to
something else you can do that and the
code will function the same I mean you
can even change this to S and if we run
the code it's going to work exactly the
same way next let's move on to the topic
of methods because right now we have a
microwave that contains data but it
doesn't do anything it doesn't function
so what I'm going to do is remove all of
this we're still going to keep Smeg
because I want to use it later but the
rest we're going to
delete and inside here we're going to
create our very first method which is
going to be called turn on because we
want to be able to turn on the microwave
and that's going to return none because
this will only execute code and I also
forgot but inside the initializer we
want to add another attribute and this
one's going to be called turned on so we
can follow or track the state of the
microwave whether it's turned on or off
and this will be of type Boolean and
it's going to be set to false initially
so as soon as we create a microwave
we're going to make sure it's turned off
as soon as we use it I mean imagine you
open a box with a microwave and it's
already turned on that would be kind of
weird anyway now that we have that
attribute we can refer to it by typing
in if self. turned on so if it is turned
on we're going to print the following
statement microwave and inside here I
want to add the brand self. brand is
already turned on so we don't turn on
that microwave twice else we're going to
set self. turned on to true and we're
going to inform the user that we
successfully turned it on so we'll copy
this paste it down here and say that the
microwave with the selft brand is now
turned on and that will be our very
first method but next I want to copy
this and paste it directly under because
we're going to create a function that
turns off the microwave so we're going
to rename that to turn off and this time
if the microwave is turned on we're
going to do the exact opposite we're
going to set self do turned on to false
and we're going to kind of flip these so
I'm going to or actually to make this
much easier I'm going to remove
everything so we don't mix it up and
just copy the statements from above so
now we can type
in that this is now turned off else if
we try to turn off a microwave that's
already turned off we're going to give
them a statement that says the microwave
is already turned off and finally I'm
going to provide one more method for
this class and this is going to be the
run method so we can actually put food
inside and give it a timer and cook that
food so here we'll say run for this
amount of seconds which will be of type
integer and once again that will return
none and obviously we first need to
check if self. turned on is set to True
otherwise we can't run the microwave but
if it is we can print that we are
running self. brand for seconds seconds
else we're going to
print that a Mystical Force Whispers
turn on your
microwave first and those will be the
methods that we will use for this class
now we can actually turn on the
microwave we can turn off that microwave
and we can run the microwave as you can
see we have a full blueprint of what the
class should look like and how it should
function so next let's try to use this
functionality so right below our
instance of Smeg we're going to refer to
it and use dot notation to actually use
these methods so right now we're going
to turn on the microwave twice and what
you're going to notice in the console is
that the first time it's actually going
to turn it on but the the second time
it's going to tell us that it's already
turned on so we have that safety
mechanism in place but once it's turned
on we can refer to Smeg and run this
microwave for let's say 30 seconds or
yeah 30 seconds and then we will turn
off the
microwave and now if we run it you'll
see that the microwave will turn on it's
going to run for 30 seconds and then
it's going to turn off because that's
exactly what we told it to do if we try
to run our microwave after we've turned
it off for 10
seconds we're going to get that Mystical
Force that Whispers to us that we should
turn on our microwave first so as you
could see it was that easy to give our
class functionality and data that we
could later use to execute certain
functionality and what's really cool
about this is that no matter what
microwave we
create we can use all of that
information the same way which means
here we're going to change it back to
bch give it a power rating of C and now
with B we can perform the same actions
we can turn it on we can turn it
off and we can try to run it for let's
say 2
seconds and it's going to work exactly
the same way microwave buch is now
turned on and then it turns off and then
the Mystical Force Whispers to us that
we can't run it without turning it on
first so with that minimal setup we
could use all the functionality once
again but there's still one last thing I
want to show you before we conclude this
video and this is the concept of Dunder
methods so for the next example I'm
going to remove all of this and keep
both of these microwaves so that we can
use them later also in pycharm I'm going
to collapse these methods because you
already know what they contain so that
we have some more space on our screen
but now that we have all of this space
on our screen I can finally get started
with explaining how Dunder methods work
in Python and to explain it I'm going to
attempt to perform this operation which
is Smeg plus bch if you try to run this
you'll immediately notice that we will
get back a type error that we tried to
use this operand with these objects and
that was not supported because we did
not Define this operation anywhere in
our class but to Define it what we need
to do is go inside our class and Define
a Dunder method so here we're going to
use the dunder method called add which
will take self which is the current
instance and which is the other instance
and the reason they call this thunder
method is because they have double
underscores so it's actually a double
uncore method and you might also hear
these being referred to as magic methods
anyway as soon as you supply this thund
method the syntax highlighting will go
away and the warning will go away as
well right now if I don't add anything
here the script will run but it's not
going to return anything so adding these
together will do nothing but inside here
you can actually do whatever you want
you can make it return whatever you want
if you add one microwave to another you
might expect to get a fusion back and in
this example we can return a string with
self. Brand Plus other do brand so that
when we actually try to add these
together what we will get back is this
Fusion and the same thing applies for
the other operators whether it's an
asterisk or a pipeline or whatever all
of these can be defined in our class so
if we want to Define for example the
multiplication operator we can do that
using the dunder mole
method and here we can
return exactly the same thing from
earlier except with an asterisk as you
can see now the next time we actually
call this it's going to give us back the
string that we specified and you don't
have to return a string here you can
actually return whatever you want it can
even be another instance of the class
but one that's actually very useful is
the string Thunder method and this is
going to return to us a string and what
we will return is the F string of self.
brand
parenthesis with the rating set to self.
power rating and what this does is give
us a legible string representation of
our class so that the next time we
actually print any one of our classes we
will get back something that we can
actually read and if we do this with bch
we will also get something legible for B
otherwise without this Stander method
we're going to get the memory address of
the class or the representation of the
class and that's also something that you
can override for example if we go here
and we Define the representation this
will return to us a string so here
instead of returning that memory address
you can return whatever you want this
will be used when you use the
representation of the class so if you
use repper on Smeg or repper on B it's
going to use this thunder method but you
might be asking if we had none of these
defined why do we get this back for the
representation well that's because
that's the default representation for a
class when you print an object if it
can't find the string Dunder method it's
going to use the representation that's
why when we use the string
representation it's going to fa to using
the string representation and one thing
I want to mention very fast because I
know this will confuse a lot of people
when they are learning python but the
difference between the string Dunder
method and the reer dunder method is
that the string Dunder method should
return something that is user friendly
something that your grandmother could
read while the representation Dunder
method should return something that's
useful for the developer for example
here we have a microwave class so
something you could return is the
microwave with the following arguments
which we have brand and power rating so
brand can equal self. brand and power
rating will equal the self. power rating
and both of those are strings so I will
surround those in quotation marks this
is a good example of something you can
return in the rapid under
method because right now when we run
this we're going to get the userfriendly
message but as soon as the developer
asks for something more specific such as
what this object actually is what they
will get back is this representation of
the object and I absolutely messed that
up because the quotation mark should be
inside the parenthesis this actually
gives information that's useful for a
developer because now they know that you
have a microwave object with a brand set
to this string and a power rating set to
this
string while the string
representation only gives us something
legible but if we change that to repper
as well
we'll get the same thing back anyway
it's time to conclude this video with
answering the question why all this hard
work well in certain situations classes
can be seen as the best way to organize
your code in the sense that all the
functionality is coupled with the class
so you will have everything you need in
one place and that just makes it easy to
create functionality that actually works
with minimal effort just like I
demonstrated with these two microwaves
we can even add a third one called
Samsung which will be of type microwave
that's going to equal a
microwave with the brand set to Samsung
and the power rating set to a and just
like that we can use all of that
functionality with Samsung we can turn
it on we can run the microwave for 1
second and then we can turn it off and
that will run straight out of the box it
was that simple to set up a microwave
and then use it with no further issue
which is just just very convenient
because if we did not use a class for
these microwaves we would have to go
through a lot of effort to create
separate microwaves so yeah that's
actually all I wanted to cover in
today's video do let me know in the
comment section down below what you
think about classes whether you're
confused about something or whether
there's something I should have covered
in more detail please let me know in the
comment section down below and I'll try
to make a followup video or I will learn
from my future lessons but otherwise
with all that being said as always
thanks for watching and I'll see you in
the next video
5.0 / 5 (0 votes)