Class Methods in Python | How to add Methods in Class | Python Tutorials for Beginners #lec87
Summary
TLDRThis video tutorial explains how to add methods to a class in Python, building upon previous lessons on attributes and object creation. It highlights the difference between attributes (the characteristics of an object) and methods (the actions an object can perform). The video demonstrates how to define and use the `__init__` method to initialize attributes and explains the importance of the `self` keyword in binding attributes and methods to objects. It also covers default values, class object variables, and provides a practical example of adding and updating followers for an instructor class.
Takeaways
- ๐ ๏ธ In this video, methods are added to a class in Python, continuing from the previous video on attributes.
- ๐ Attributes represent the data objects possess, such as name, phone number, and address, while methods represent actions that objects can perform.
- ๐ก The `__init__` function is introduced, which is used to initialize attributes when creating an object of a class.
- ๐๏ธ Methods in a class are similar to functions but are attached to objects, making them distinct from standalone functions.
- ๐ The `self` keyword is crucial in class methods, binding the method to the specific object it is called on, allowing it to access that object's attributes.
- ๐ Class object variables, like `followers = 0`, are shared by all objects of the class, making them accessible without explicitly initializing them for each object.
- ๐ The method `update_followers` is created to modify object attributes (like increasing a follower count), showing how methods interact with attributes.
- ๐ฅ Parameters passed to class methods don't need to be attributes of the class (e.g., `subject_name`), but attributes (like `self.name`) must use the `self` keyword to access.
- โ๏ธ Methods allow objects to perform actions, such as updating attributes based on interactions (like increasing a follower count when someone follows).
- ๐ค Understanding the difference between passing arguments to methods and using attributes is key when designing classes with both attributes and methods.
Q & A
What are the two main components of a class in Python?
-The two main components of a class in Python are attributes and methods. Attributes represent the properties of the object (e.g., name, address), while methods represent the actions the object can perform (e.g., teaching).
What is the purpose of the __init__ method in a Python class?
-The __init__ method is a constructor used to initialize the attributes of a class when an object is created. It assigns values to the attributes and ensures the object is properly set up with the required properties.
Why is the 'self' keyword important in Python class methods?
-The 'self' keyword refers to the instance of the class on which the method is being called. It allows access to the attributes and methods of the specific object, ensuring that operations are applied to the correct instance.
What is the difference between a class attribute and an instance attribute?
-A class attribute is shared by all instances of the class, while an instance attribute is specific to each object. In the example, 'followers' is a class attribute (shared by all objects), whereas 'name' and 'address' are instance attributes (specific to each object).
How can you call a method of a class in Python?
-To call a method of a class, you use the object name followed by the method name. For example, 'instructor1.display()' calls the 'display' method on the 'instructor1' object.
What happens if you don't provide a return statement in a method?
-If a return statement is not provided, the method will automatically return 'None'. This is why in the script, the output included 'None' until the return statement was adjusted.
Why did the script produce an error when 'self.subject_name' was used instead of 'subject_name'?
-The error occurred because 'subject_name' was passed as a parameter, not an attribute of the class. 'self' is only used to access attributes of the object, and 'subject_name' was just a local variable in the method.
What is the purpose of the 'update_followers' method in the script?
-The 'update_followers' method increases the follower count of an instructor by one each time it's called, simulating someone starting to follow that instructor.
What is the significance of default values in class attributes?
-Default values in class attributes, such as 'followers = 0', ensure that every object starts with the same value for that attribute unless explicitly changed. This avoids needing to pass the same value every time an object is created.
How can the script be extended to handle both 'followers' and 'following' counts for an instructor?
-The script can be extended by adding a new attribute, 'following', to track how many people the instructor is following. A corresponding method could be added to update the 'following' count whenever the instructor starts following someone.
Outlines
๐จโ๐ซ Introduction to Class Attributes and Methods
This paragraph reviews the previous video's topics on creating a class, adding attributes, and defining objects. It introduces the concept of attributes as properties of an object, such as name and address, and methods as actions the object performs. The video will now focus on adding methods to a class, building on prior knowledge of the `__init__` function and class structures. The use of Pascal case for class naming conventions is also briefly discussed.
๐ Adding Methods to a Class
The explanation begins with creating a new file for class methods, using the example of an instructor class with name and address attributes. It demonstrates how to pass values to these attributes using the `__init__` function and explains the role of `self` in binding attributes to arguments. The instructor objects are created with name and address attributes, and their values are printed to show how attributes can be accessed. This paragraph reinforces the concept of the `self` keyword and how it dynamically refers to the object being created.
๐ Introducing Default and Class Object Variables
Here, the concept of default attributes and class object variables is introduced. The `followers` attribute is set with a default value of 0, either passed in the `__init__` method or as a class object variable. The paragraph explains that class object variables are shared across all instances of the class, whereas instance variables are unique to each object. Examples are provided to show how these variables work, emphasizing the distinction between class object variables and instance attributes.
๐ง Defining and Calling Methods on Class Instances
This section covers the process of adding methods to a class. The structure of a method within a class is similar to defining a function, with `self` being automatically passed as the first argument. The example of a `display()` method is used to demonstrate how methods are called on objects and how `self` binds the method to the specific object instance. An error when calling a method without `self` is explained, and the use of the method with the correct syntax is demonstrated.
๐ก Handling Return Values and Method Refinement
This paragraph explains the behavior of functions that donโt have an explicit return statement, highlighting that they return `None` by default. It demonstrates how this can lead to unexpected output and shows how to refine the method to avoid printing `None`. The example is extended to include more functionality in the method, such as printing a personalized message using an objectโs attributes (e.g., name). The role of `self` in accessing these attributes within the method is further clarified.
๐ Passing Arguments to Methods
The paragraph introduces the idea of passing arguments to methods, using an example where a subject name is passed to the `display()` method. The difference between using an instance attribute (`self.name`) and a method argument (subject) is discussed in detail. It clarifies why `self` is used for attributes but not for passing simple arguments, using errors as examples to illustrate the correct usage.
๐ Updating Object Attributes with Methods
A new method, `update_followers()`, is introduced to demonstrate how methods can modify the attributes of an object. The method increments the `followers` count of an instructor by 1 when a new follower is added. The example shows how calling the method on different objects affects their individual `followers` attributes. The paragraph emphasizes the use of `self` in updating object-specific attributes and explains how to pass additional arguments to methods when necessary.
๐ Managing Multiple Objects and Their States
This section expands on the `update_followers()` method by applying it to multiple instructor objects. The followers count is updated for each instructor, and the differences between their follower counts are printed to show how each object maintains its own state. The paragraph demonstrates the use of methods to interact with and modify object attributes dynamically, encouraging the reader to experiment with adding more objects and updating their attributes.
๐ฏ Applying the Concepts: Followers and Following Counts
The final paragraph encourages viewers to experiment further by creating additional instructor objects and managing both follower and following counts, drawing parallels to social media platforms like Instagram. The suggestion is to explore how followers and following counts can be tracked for each instructor, using methods to manage these attributes. The paragraph concludes by introducing the upcoming video, which will feature an exercise based on the concepts discussed.
Mindmap
Keywords
๐กClass
๐กObject
๐กAttribute
๐กMethod
๐กself
๐ก__init__ method
๐กPascal Case
๐กClass Object Variable
๐กF-string
๐กPositional Arguments
Highlights
Overview of adding attributes and methods to a class in Python.
Attributes represent the characteristics an object has, like name, phone number, etc.
Methods represent the actions an object performs, like teaching, displaying information, etc.
Introduction to the `__init__` method to initialize class attributes.
Explanation of `self` keyword: it binds attributes to the arguments passed during object creation.
Naming conventions for classes, like using Pascal case (capitalized first letter).
Demonstration of creating and passing attributes like `name` and `address` when initializing objects.
How the `__init__` method is called each time an object is created.
Use of default attribute values like `followers = 0` for every object in the class.
Difference between instance attributes (those inside `__init__`) and class-level attributes.
Introduction to methods as functions attached to an object and how to define them using `def` keyword.
Importance of using `self` in methods to bind them to the specific object they're called on.
Explanation of why methods return `None` if no explicit return statement is given.
Using f-strings for dynamic printing inside methods, such as `Hi, I am {name}`.
Creating methods to modify class attributes, such as updating the follower count for an instructor.
Adding and passing arguments to methods for customized behavior, like specifying the subject an instructor teaches.
Transcripts
in the previous video we have seen how
to add attribute to your class right how
to create your own class how to create
object and then how to add attribute
right now remaining is obviously in
class we are having like attribute as
well as methods attribute means the
object the you know attributes are
basically the things that the object has
like I am if I am an object then I'm
having my name my phone number address
these are objects and methods are the
thing that the object does like I do
like I do teach right so these are the
methods so now in this video we'll see
how to add methods to your class right
so we have seen in the previous video
init function as well how to initialize
the attributes right so you please you
first watch that video and then come to
this video right then you will get it
better because for this to understand
this video you need to know what is that
underscore underscore in it underscore
underscore in bracket you have just
passed cell what is that function right
okay now
this we have done in the previous video
see the class was instructor
okay the class name it should be capital
i
uh Pascal case uh the convention is
Pascal case v used to name the class but
if you you know take small I then it's
also fine it will not give any syntax
error but
it is like the convention is basically
to differentiate the class name variable
name function name and like this right
okay now
we will add methods to our class
so we are going to create a new file
here
class methods Dot py
and let's take we are having same
example I'll be taking we are having a
class instructor right and now that init
function
and we are passing like two two
parameter here one is the name and
second one we have passed that was
address so how to assign the value then
self Dot
name of the attribute is I'm taking name
and here name
so see these this and this should be
same the parameter name and this value
this should be
same this name can be different
it is not compulsory that this this name
of this attribute should be same as the
parameter name right these things we
have discussed
you know in previous video
so let's take address and this is what
address I am assigning
and if you create
an object of the class instructor then
this time we need to pass
if I run this then C you will get an
error
this instructor is missing two required
positional argument line number five
here we are creating an object so you
have to pass name as well as address so
one passing like name is equal to Jenny
and suppose address is
gurgaon
so this time it will not give any error
and if you print suppose instructor one
wrote name then it will give you Jenny
this is how we can access right so you
know the self is just a keyword that
bind the the the attribute
attributes to the argument receive so
this init function would be called every
time you create an object so if you
create
two object then two time this init
function would be called right so first
time it would be called while we are
creating this object at in Fifth Line
while we are executing the Fifth Line so
self means self is referring to the
actual object now so self is referring
instructor one so self is instructor one
at this point of time so instructor one
dot name whatever name you will pass
Jenny instructor one dot address
whatever address you will pass that is
right now if I create another object
same
and instructor 2 is suppose
Gia
so at this point of time also this init
function would be called every time you
create an object this function would be
called every time so now if we are
calling
if this function is being called during
this time then this time the self is
referring to instructor to this object
so now self value is you can assume like
instructor 2 and name value is Gia
addresses same gurgaon so now selfish
instructor 2 dot name gr instructor to
dot address
I hope now you got the basically the
other working why we are using this self
here right it is binding
the now object attribute to the argument
received right okay
now we we are we we have a default also
like default
attribute that is followers because it
is not compulsory that every teacher is
on phone every teacher is on sorry self
dot Instagram
so by default rather than passing zero
zero zero for every teacher if you have
created 10 object then every time you
will pass zero zero zero as an argument
if you write down here followers
as a parameter but set the default value
so by default you don't need to pass 0
here now followers would be 0 0 for
every object you create right or rather
than this one more ways what you can
create a class object variable here
followers is equal to 0 rather than here
so now this here see we are not using
any cell keywords self growth follower
no because these are outside of this
init function so this is what a class
object variable for every object that
you create from this class instructor
instructor class the follower this
attribute would be
Associated to every object and for every
object the value of polar would be zero
so see if you want to check then if you
want to print like instructor
one dot
followers then you will give you will
get 0 see
although we haven't initialized this we
are not passing any follower here we
haven't initialized here self dot
follower zero so where from where this
is taking the value follow a zero for
instructor 2 also follow us value is 0.
right now this is what just a quick
recap of the previous one because we are
just adding the attribute we have just
started attribute now how to add methods
so methods are basically
simple you can say these are functions
like if
same
what is the syntax of creating a
function def function name and round
bracket and if you want to pass any
parameter just pass the parameter right
same
you can say that um
syntax is here depth function name
suppose simple I am taking display
function
and if you something like this if you
put these bracket then automatically
here you will get self keyword
because this is compulsory
on every if you call this display method
on this instructor one then the self
will bind this function to
this object on which you are calling
this display so at this point of time
self is a structure one if you are
calling this display function on
instructor 2 object second object then
at that point of time self will become
instructor 2. so it will basically bind
right
the function or the method
to the object on which you are calling
this method so means a function becomes
method when it is attached to a
particular object right that is why we
are not calling it function we are
calling it method so here I am simply
printing
like print
and
suppose I print hi
that's it this is the simplest example
I'm taking right and on instructor 1 how
to call this method now if you call this
if you access this method using first
object
then simply we cannot write down here
like display
and just call display function no it
will give error
see the name display is not defined in
line number 11 right
so you have to attach this
with the object name
so on instructor 1 I want to call this
display function so instructor 1 dot
display right this is how an object can
access
the method of a class or attribute of a
class object name dot then whatever you
want to access display okay if you run
this
see you are getting
Jenny high and C yeah you are getting
none here
so
where is the problem why you are getting
this none
so please pause the video and try this
out why you are getting Jenny High then
none sorry
so see the problem is
it will print Jenny now we are calling
in print we are calling instructor one
dot display now we are calling this so
control would be here right now self is
this time instructor one so it will
print in display we are having just
print hi so it will print hi now you are
printing means whatever this this will
return that thing we want to print but
here we are not
writing any return statement
so if you don't write any return
statement then definitely we know every
function is going to return something if
you do not write any return statement
then it will return none so that is why
it is returning none here and we are
printing none we are getting the answer
Jenny higher than none so just remove
this print
and simply call display function on
instructor one object right now let's
run this
see Jenny and hi
right I hope you got this
now this is the simplest example you
have taken now suppose basically methods
are basically you know the actions we
perform on the attributes may be using
the values of the attributes and do
something or maybe modify the attribute
value and do something and return some
result
that is obviously the use of methods it
is not about you know any use like just
print hi but this is just to make you
understand like how you can define a
function right now if you want to print
if suppose I want to call this one here
so it should print hi I am I am genuine
because instructor one name is Jenny
so can you do this
yes you can pause the video and try this
out
so hi I want to print hi
I am gen so from where I will get Jenny
from the name attribute
in name attribute of instructor 1 I have
gen so from the name attribute just
fetch the value so directly if you write
name here so obviously you have to use F
string
then what do you think
you will get Jenny or not let's run this
C
it is giving an error
here display line number two and line
number eight High I am this name name is
not Define
name is not defined just it's just a
variable and we are using here not just
simple variables attributes you have to
attach this variable to a specific
object
for Which object you are using this name
obviously instructor one so rather than
obviously instructor one dot name here
you will write
self one note name so sorry self dot
name because here self is referring to
that particular object on which you are
calling this display function so here
cell phone is instructor one so
automatically it will fetch the name
from instructor one hi I am Jenny
right I hope you got this so the self
keyword you will get you know many times
within this class only not outside of
the class we are using cell we are using
within this class only cell right and
my name is Jenny and suppose I want like
I teach python
so
I want to pass a parameter an argument
as an argument what subject I teach so
for that suppose in display I want to
pass like I teach
python
so for this obviously you need some
parameter to fetch to you know uh store
that value that string so
I'm just taking a parameter name subject
name right hi I am the name and
I
teach
now how you will fetch that thing I
teach the subject name the python python
it should print hi I am Jenny and I
teach python
so you can pause the video and try this
out
okay I hope you have done this and you
just need to write down here
subject name no need to write down self
load subject name
first let's run this and see
I'm Jenny and I and I teach python why
you are not writing here self
dot pipe so uh dot subject name if you
write this thing let's run this and you
will see you will get a error message
like in line number 12 here you are
calling this and then in line number
eight line number eight means
uh
here here you are defining this function
right now what this is this line
an attribute error it's an attribute
error instructor object has no attribute
subject name because when you access
self Dot like this then this should be
an attribute
because I am using self dot name because
name is an attribute of
that object
it's an attribute in this class but
subject name is not any attribute we
have only two attribute name and address
right so how this self can bind
because this can only bind the attribute
this attribute to that particular object
but subject name is not any attribute we
are just passing
an argument so simply you will pass
Python and it will take the value from
subject name python no need to write
down here self load
subject name I hope now you got the
difference why I am writing a self dot
names and here just subject name we are
not passing any name here and we are
still getting name Jenny
right because it is an attribute of the
object and we are passing subject name
and we are getting obviously the subject
name right
so now
if you don't know like maybe subject
name if I pass like python simply python
then it will give error
python is not defined in line number 12.
right
because this this is expecting a string
as an argument
so like the proper ways you can just
write down here in comments like hash
and
this will accept subject name as a
string
right or expect a string
as a subject name so to Define that
thing you can write down here that
proper thing so that if anyone see your
program then he or she will get yeah
they have to pass
string right so this should be string
here
and if suppose if you want to update the
follower count right so if suppose I
take another
function depth
update followers right and obviously it
will be self
and
on instructor one I am calling this
function on instructor 1 Dot
update follower right and here
I want I just pass a name it means that
person has started following instructor
one so the follower count of instructor
1 would be increased by one right so the
follower count of
self load
followers of that object on which we are
calling this function so definitely you
will write yourself self dot followers
count will increased by one right so
here I am passing a suppose name
like pile means pile has started
following
instructor one and instructor one is
Jenny means pile has started following
Jenny so Jenny's followers would be plus
one right and now if you print
like instructor one dot
followers
then see what you will get
okay it is giving an error because in
line number 17 here we are passing
instructor type error it takes one
positional argument but two are given
okay
to accept obviously to accept this pile
you have to
give up obviously the parameter name
because one is self to and one is pile
for pile to accept pile you have to give
a parameter name follow our name
see now hi I am Jenny I teach Python and
one now follower count of Jenny is one
it's starting it was Zero now see you
have updated the attribute
right
so this also you can do if if suppose I
have one more instructor instructor too
and on instructor two for instructor two
I am just printing
followers
then it will give zero
see one was for instructor one and at
last we are getting zero so that is for
instructor two because on instructor 2
you haven't pulled this update follower
function right if you call this update
folder function on instructor 2 as well
like instructor two Dot
update follower and
suppose Jenny has started following
instructor to instructor 2 is Gia
so let's run this
now both are having
two two obviously you have to
okay
still zero because
we are printing
here so after update after calling this
update you have to you have to print
instructor to wrote follower right see
now both
one and one
for both it's one and one right four
over count
so this is how you can add methods and
so you can I hope you got how to add
methods and when you use self load the
name and like without self uh where when
you can write down any variable name or
attribute name sorry this is not
attribute this is just a variable right
or argument you are passing
fine
so now you can try this out like maybe
you can update
for maybe you can create two more
objects and you can update the followers
right or maybe you can try to print like
follow account as well as following
count if I started like someone GS
started following me so my follow
account would be one and Gia's following
count would be one right followers and
following if you are on Instagram then
you know this thing right followers and
following two things are there
so you can play around with this code
So based on this we'll be discussing one
exercise in the next video so I'll see
the next video bye take care
5.0 / 5 (0 votes)