Self and __init__() method in Python | Python Tutorials for Beginners #lec86
Summary
TLDRIn this video, the speaker continues their Python Object-Oriented Programming series by discussing how to add attributes and initialize objects in a class using the `__init__` method. They explain the role of constructors, the `self` keyword, and how to set default values for attributes like Instagram followers. The video emphasizes simplifying object creation by reducing code lines and concludes with an assignment for viewers to practice creating new objects with attributes. The next video will cover adding methods to the class.
Takeaways
- 📚 The video continues a Python programming series focusing on object-oriented programming.
- 🧑🏫 The instructor discusses creating classes and objects, building on concepts from the previous video.
- 🏗️ The key topic in this video is adding attributes to a class and introducing the `__init__` method, which serves as a constructor.
- 🔑 The `self` keyword is explained as a way to reference the current object when creating attributes or methods within a class.
- 💡 The purpose of the `__init__` method is to initialize the attributes of an object automatically when the object is created.
- 🔄 Each time an object is created, the `__init__` method is called to set up the initial state of that object with the given parameters.
- 📝 Examples are provided on how to add attributes like `name`, `address`, and `followers` to a class and initialize them using the constructor.
- ❗ The instructor emphasizes that attributes must be accessed using `object.attribute` syntax and demonstrates how this works.
- 🚀 Default values for attributes (like setting default Instagram followers to 0) can be added, reducing the need for repetitive code.
- 📌 An assignment is given at the end, asking viewers to create more instructors with name and address attributes, and print their information.
Q & A
What is the purpose of the `__init__` method in Python classes?
-The `__init__` method in Python is a special function that acts as a constructor. Its primary purpose is to initialize the attributes of a class when an object is created.
Why is the `self` keyword used in class methods?
-The `self` keyword is used to refer to the current instance of the class. It allows the method to access and modify the object's attributes and ensures the method operates on the correct object.
How do you assign attributes to an object of a class?
-Attributes can be assigned directly to an object using dot notation, like `object.attribute = value`. Alternatively, attributes can be initialized inside the `__init__` method by assigning values to `self.attribute`.
What happens if you don't pass any parameters to the `__init__` method?
-If no parameters are passed to the `__init__` method, and it expects them, Python will raise a `TypeError`, stating that required positional arguments are missing.
What is the advantage of setting default values for parameters in the `__init__` method?
-Setting default values for parameters allows you to create objects without providing values for those parameters. This is useful when certain attributes are optional or have a standard default value.
Can you modify the attributes of an object after it has been created?
-Yes, attributes of an object can be modified after its creation using dot notation, such as `object.attribute = new_value`.
What is the difference between a class attribute and an instance attribute?
-An instance attribute is specific to each object of a class and is set using `self.attribute`, while a class attribute is shared across all instances of the class.
What does the error 'missing required positional argument' indicate?
-This error occurs when a function or method, like `__init__`, is called without providing the necessary arguments it expects, leading to an incomplete call.
Why is using a class beneficial for managing multiple similar objects?
-Using a class allows for better organization and reusability of code, as it provides a blueprint for creating multiple objects with similar attributes and methods, reducing repetition and potential errors.
How would you create a new object with attributes in a Python class?
-To create a new object with attributes, define the class with an `__init__` method that initializes the attributes. Then, create an object by calling the class and passing the necessary parameters to the `__init__` method.
Outlines
📚 Introduction to Object-Oriented Programming in Python
The speaker introduces the topic of Object-Oriented Programming (OOP) in Python, building on concepts discussed in previous videos such as classes and objects. They mention that the current video will focus on adding attributes and methods to classes, particularly the `__init__` method (Constructor) and the `self` keyword. The speaker also highlights the importance of constructors for initializing object attributes, which will be demonstrated in this video.
💻 Overview of a Python Programming Competition
The speaker briefly shifts focus to announce a Python programming competition called Ultra Combat, hosted by Anacademy. It offers up to 90% scholarships and various rewards such as MacBooks and smartphones. The competition, geared toward GATE and ESE aspirants, consists of 40 MCQs to be answered within 120 minutes. Participants can register for free using a provided code, and the event is scheduled for July 23 at 11 AM. The speaker encourages viewers to check the description box for further details and relevant links.
🧑🏫 Explaining Class Attributes in Python
Returning to the Python topic, the speaker explains how to add attributes to a class, using an example of an 'Instructor' class with attributes like `name` and `address`. The speaker demonstrates that attributes are specific to objects, and to access these, you must reference the object (e.g., `instructor1.name`). They show how assigning attributes directly to an object can lead to inconsistent and inefficient code, especially when handling multiple instructors. This highlights the need for a constructor (`__init__` method) to automate the process of initializing object attributes.
🔧 Introducing Constructors and the `__init__` Method
The speaker introduces the concept of constructors in Python using the `__init__` method, which automates the initialization of object attributes when an object is created. They clarify how `self` binds attributes to the current object and demonstrate the syntax of defining attributes such as `name` and `address` within the constructor. By automating attribute initialization, constructors help streamline object creation and reduce code repetition, making it easier to manage large numbers of objects.
📝 Example of Using Constructors to Simplify Code
The speaker walks through an example where the `__init__` method is used to create two instructor objects, passing attributes like `name` and `address` directly at object creation. They highlight how omitting required parameters results in errors and explain the role of `self` in binding values to the correct object. The example demonstrates how constructors simplify the code by eliminating the need to manually assign each attribute to every object.
🛠️ Using Default Values for Attributes in Python
The speaker explains how default values can be set for optional attributes like `Instagram followers`, which not all instructors may have. By setting a default value (e.g., `followers = 0`), the speaker shows how Python allows flexibility in creating objects without specifying every single attribute. This feature saves time and code, as default values can be overridden when necessary, but they prevent repetitive zero assignments for attributes not applicable to all objects.
💡 Assignment and Upcoming Lesson on Adding Methods
As the video wraps up, the speaker assigns viewers the task of creating two more instructor objects and printing their `name` and `address` attributes. The speaker teases the next video, which will cover adding methods to classes, building on the concept of attributes by focusing on what the objects can do, not just what they are. The video concludes with a thank-you message and an invitation to continue learning in the next installment.
Mindmap
Keywords
💡Object-Oriented Programming (OOP)
💡Class
💡Object
💡Attributes
💡__init__ Method (Constructor)
💡Self Keyword
💡Methods
💡Default Values
💡Gate and ESE Combat
💡User-defined Data Type
Highlights
Introduction to object-oriented programming in Python and recap of previous concepts like classes and objects.
Discussion on adding attributes and methods to a class, focusing on how to initialize objects.
Explanation of the `__init__` method and its importance in initializing object attributes when creating an object.
Introduction of the `self` keyword and its role in referencing the actual object that is calling the method.
Demonstration of how to create object-specific attributes using `self` and initializing them within the `__init__` method.
The concept of a constructor in Python is explained as the `__init__` method that runs automatically upon object creation.
Explanation of how to pass arguments like name and address while creating an object to initialize its attributes.
Detailed walkthrough of assigning attributes to individual objects and how it reduces redundancy in the code.
Illustration of the problem of assigning attributes manually for multiple objects and how the constructor solves it.
The `__init__` method is demonstrated by passing custom attributes such as name and address to multiple instructor objects.
Example of handling default values for attributes, such as Instagram followers, where not all objects require a specific value.
Using default values in constructors to simplify object creation when some attributes are optional or have common values.
Demonstration of printing object-specific attributes like name and address for multiple instructor objects.
Assignment to create additional instructors and practice initializing and printing their attributes, reinforcing the concepts.
Teaser for the next video, which will cover adding methods to classes, further enhancing the functionality of object-oriented programming.
Transcripts
hey everyone I hope you all are safe and
doing good so in the series of learning
Python programming language we are
discussing object-oriented programming
in python in the previous video we have
seen like what is in class what is an
object how to create a class how to
create an object why do we need classes
this thing we have discussed right
but we haven't like we have created our
own class but we haven't added any
attributes or methods in that class so
that thing we'll be discussing in this
video
how to add attributes what is that init
method underscore underscore N8
underscore underscore and in bracket a
self keyword is passed as a parameter
right so what is that method what is
basically the fund of Constructor
right how to initialize objects while
creating those objects of a class so
these things will be discussing in this
video right but before that this one
will tell you something it is especially
important for gate and ASE as parents an
academy is back with combat and this
time it is ultra combat Yes you heard it
right now you have a chance to get up to
90 scholarship and many rewards such as
MacBook Dell laptop Samsung Mobile and
many more and this Ultra combat for gate
and escs parents would be on would be
conducted on 23rd of July and the timing
is 11 am
and what how many question you will get
the pattern is 40 mcqs you will get and
the time limit would be 120 Minutes
right and what is the syllabus the
syllabus will be General aptitude
engineering mathematics and Technical
and the most important thing is you can
enroll for this Ultra combat for free
you don't need to pay anything no
registration fee nothing no charges
right so the link for you know
registration to enroll in this Ultra
combat would be in the description box
of this video for all the branches
mechanical civil CS electrical right and
you can use my code jkl10 to enroll for
free in this combat right so all the
relevant links and information you will
find in the description box of this
video you can go and check out okay now
let's see this was the class we have
created in the previous lecture the
class instructor and we have done
nothing here no attribute nothing else
just pass and we have created one object
and if you find out the type of this
object then it will give you instructor
right just forget about this and
response for main underscore that also
will I'll tell you in later videos so
the classes this instructor so class
means basically it's a user defined data
type
that it has a blueprint to create object
okay now how to add attributes see if in
instructor obviously the instructor is
having some name or ID or information
the main information so one way is
instructor one
instructor one
dot name I am assigning like maybe
pile
right you cannot simply write down here
just name is equal to Pi
that would be simple a variable but now
this name is an attribute of this
instructor
this instructor is an object that is why
we are writing instructor dot name this
name is now attached with this
instructor with this object right so
that is why this is now attribute one
more thing if you want to check like
instructor
Dot
address is equal to
Delhi
right and if you want to fetch if you
want to print this information then how
you can press simply we cannot write
down like print name
let's run this and what see what you
will get
name is not defined
because name is
its name is what instructor one dot name
it's not just simply name a variable no
it's now an attribute of this object so
you must write here instructor 1 dot
name this is the syntax right if you
assign value to an object like this and
if you want to fetch the value so
instructor one dot name this time it
will give pi
right
like this if like I have a YouTube
channel I want to hire now 10 instructor
to teach different different subjects
and like the attribute of this
instructor these instructor would be
many attribute I want to store like name
address and like maybe ID and phone
number has camera has laptop has books
these are simple attributes
so for one instructor I want to store
every information so same you can
instructor one note name this instructor
OneNote address instructor one dot ID
instructor one dot phone number
instructor one dot has camera and like
this you can write down these lines
and like this if I want to create one
more instructor
so in that case what will happen
instructor 2 is equal to this same
method now instructor two dot name and
instructor two dot address and if I want
to print instructor two dot name that is
also fine it will print pile and
okay there is some error here
like this so it will give let's just
rename this otherwise it will give same
name so like Jenny
so it will give pile and jelly
like two name like this if you want to
store information of 10 instructor then
definitely it
is not easy because we are it's so
hectic so many number of lines
right and maybe like name here I'm
writing name here I'm writing username
over here I'm writing address or simply
instructor address maybe I can write
here instructor address
so the name of these attributes
would be maybe different
for each object for each object for each
instructor right so it would be not easy
to manage the information like this
right and definitely now what is the use
of class if we are writing this kind of
thing that we can do with the help of
simple variables we can create different
variables for each instructor of each
thing right
now for this
okay now class comes into picture
now here
we have for this thing we use the you
can say the concept of Constructor if
you are from C plus background if then
you must have heard about Constructor
right if not it's okay I'll tell you
here
so basically the task of an Constructor
is to initialize
the data members to assign values to the
data members of a class
when
an object is created
so Constructor will basically allow us
to specify what would happen when we
create this object when we create an
object what would happen
with the help of Constructor we can do
this thing we can initialize
the attributes the members of the class
while creating we don't have to write
down like instructor one dot name one
dot address and we have to initialize
separately no
right so here we have a special function
that is Def
and
this
init function so see it is not just a
simple function
because it is special one because it is
having underscore underscore init
underscore underscore then in bracket
also we have like cell it's
automatically I haven't written C cell
for like this
if you write down this thing simply i n
i then see you will got this thing self
it's predefined predefined right so it's
a special method
and python interpreter no it is a
special method and what it will do
python intermittent python interpreter
no knows about this method very well
right
now self is a key word why we are
passing this self that also I'll tell
you so in C plus plus we are having
Constructor to initialize object in
Python we are having this method init
method to initialize the object
to initialize the data members of a
class while creating an object
right
so same as Constructor it is doing the
same task
okay now see
and one more thing this init function
would be called every time you create
an object
right so see if you want to check out
this thing you can write down something
like this print
creating a new object I'm not writing
anything I'm just printing here creating
a new object and let's run this
see first creating a new object because
here
we are
creating an object so creating a new
object then pile it will print file
right then again creating a new object
and Jenny it will print so two time
this this would be printed so two time
you have called this init function right
this function has been called so this
one object we have created another
object we have created so every time you
create an object of a class this init
function would be called every time
right and it is used to like initialize
the attributes of that particular object
right
so the self is indicating it is
referring the actual object on which
right now we are calling this function
on which this function has been called
right now so if this function has been
called right now on this object
instructor 1 so the self is instructor
one
if next time this init function has been
called during this line instructor 2 is
equal to instructor so now at this point
of time the selfish instructor 2 so it
is referring to the actual object
right so when we are calling this then
it will initialize the instructor 1
object attribute this time at this point
of time it will initialize instructor to
object attribute so I hope now you got
why we are using this self keyboard here
right if you are still not getting it's
okay we'll do some practice here so I
want to like
pass name and address so like two
parameter we can pass name
and
address any name you can take right
and let's just remove the slime
right
now how to initialize the attribute of
the instructor only two attribute I am
taking name and address that's it so you
have to write down the self keyword cell
Dot
the name of the attribute what you want
the name of that review so I want name
is equal to
this is not compulsory that this name
this parameter name and this should be
same it may be different right so the
self name is equal to whatever argument
you will pass and that we will fetch
here in this parameter name name so you
have to write down here this name
right see the color this name and this
name is having same color but this name
is having different color so here the
attribute name you can take any things I
can take here like
instructor underscore name that is also
fine
Constructor and Square address but I am
taking here name that's it
so
self dot second attribute name I am
taking just address is equal to
this address
let's just take here
let's
rename this instructor underscore name
the parameter name so here you need to
pass
instructor underscore name now you got
the difference
this parameter name and this name should
be same and this attribute name you can
take
any name right it should not be
same with this parameter name right
okay now you don't need to assign the
value initialize the object attribute
like this what we can do just remove
these two lines and
while creating the object obviously this
init function would be called so now it
is expecting to pass these two parameter
name and address so here only I can pass
like Jenny and in address I am passing
like
Maybe gurgaon
right
and let's just comment out these lines
for instructor 2 and let's just print
instructor one dot name let's run this
and it will print the name
right so obviously it will reduce the
number of lines of code right
now for instructor to same
so instructor 2 and instructor see now
if I don't pass anything here and let's
run this
so you are getting an error
see
in line number 10 in line number 10 in
this line in this line
while you are creating this object then
this init missing two required
positional argument instructor name and
address right
so obviously this function would be
called init method would be called while
you are creating the object and you need
to pass these two parameter not three
maybe you think self is also there but
self is just a keyword to bind the
actual object
with the values right so by default self
at this time would be instructor 2 and
by default self at this time would be
instructor one so you don't need to pass
the value for self it is just a keyword
right so self is like basically just a
keyword to bind
it will bind the
objects attributes to the argument
received right
obviously now you need to pass two
argument here so I am passing like pile
and address is like
Delhi now this is fine you will not get
any error now you can face this
information right like this if you want
to create 10 instructor then definitely
now it would be easy and less number of
less lines of code
right
so this is the use of the class and this
init method I think it is clear to you
guys what is this in it what is the self
and all right now
if you want to pass like by default
let's take one example uh I want to pass
the Instagram follower of each
instructor maybe the instructor doesn't
are not on Instagram right most of the
teachers are not on Instagram so they
are having zero zero zero followers
right so that information is not
mandatory right obviously everyone is
having name everyone is having some
specific address so that for sure but
it's not compulsive that everyone is on
Instagram and having some follower
account right so if I pass here this is
the case if I pass here like
Instagram underscore
if I pass a parameter Instagram
underscore follower so maybe Jenny is
not like on Instagram so you need to
pass here zero and for pile also maybe
you need to pass zero so maybe 10
instructor for every instructor the
count is zero so why you are passing
zero zero it's just a waste of you can
save time
and they're not no logic to pass zero
zero zero so what we can what we can do
rather than
making this
in compulsory argument to pass we can
set default value of this parameter cell
Dot
followers is equal to 0.
and now see it's not like that if I am
on Instagram and I have some followers
so right now every object will be having
zero follower of this class all the
objects right but we can modify this
this attribute specifically for any
object like for Jenny if I want to
modify then I can modify that is also
fine that also will see
right but for now you have to be clear
this thing like you can pass default
value also for any attribute now for
every if I want to print like print and
instructor one dot
followers
now it will print a zero
see Jenny and zero because by default
the follower count for each object of
this class would be zero because we have
set a default value right
now I hope you got the idea like how to
add attributes how to initialize the
attributes of an object what is the you
know use of this init function what is
this self keyword like this
so now one assignment for you is okay
this is the class and all now you have
to create two more instructor right
passing the name and address and you
have to print the information name as
well as address for each instructor for
the two instructor right
so now that's it for this video in the
next video we'll see how to add methods
these are just attributes we haven't
added still methods what the instructor
will do we have just added what he or
she has not what he or she does right so
that thing we'll see in the next video
so thanks for the next video then bye
thank you
Ver Más Videos Relacionados
Class Methods in Python | How to add Methods in Class | Python Tutorials for Beginners #lec87
Classes and Objects in Python | OOP in Python | Python for Beginners #lec85
CH01_VID02_Encapsulation
Class Objects & Constructors | Godot GDScript Tutorial | Ep 16
Python OOP Tutorial 1: Classes and Instances
ICS2O - Lesson 5 - Introduction to Alice
5.0 / 5 (0 votes)