Python OOP Tutorial 1: Classes and Instances
Summary
TLDRThis video tutorial introduces the concept of classes in Python, emphasizing their importance in modern programming for logical data and function grouping. It covers the basics of creating and instantiating classes, explaining the distinction between class and instance, and the use of instance variables. The video demonstrates how to utilize the special `__init__` method for automatic attribute assignment and introduces the creation of methods, using a simple 'Employee' class as an example. It also highlights the importance of the 'self' argument in methods and the difference in calling methods on instances versus classes. The content is aimed at beginners, providing a solid foundation for understanding object-oriented programming in Python.
Takeaways
- 📚 Introduction to Python classes and object-oriented programming concepts.
- 🎯 Classes are used to logically group data and functions for easy reuse and expansion.
- 🏗️ The basics of creating and instantiating classes are covered, emphasizing their structure and usage.
- 🔍 Explanation of the difference between a class (blueprint) and an instance (unique implementation).
- 🌟 Instance variables store unique data for each instance, while class variables are shared across all instances.
- 🛠️ Use of the special `__init__` method to automatically set up instance variables when creating new instances.
- 📝 Manual assignment of instance variables is error-prone and not efficient; the `__init__` method mitigates this.
- 📌 Instance methods are defined and used to perform actions on the instance data, with `self` referring to the instance.
- 🔑 Demonstration of a method to display an employee's full name, highlighting the use of instance variables within methods.
- ⚠️ Importance of including the `self` argument in instance methods to reference the instance data.
- 🔄 Clarification on invoking methods using both the instance and the class name, and how `self` is handled in these cases.
Q & A
Why are classes useful in programming?
-Classes are beneficial because they allow us to logically group data and functions together, making it easier to reuse and build upon the code when necessary.
What is the main difference between a class and an instance of a class?
-A class serves as a blueprint for creating specific objects, while an instance is a unique object created from that class with its own set of attributes and methods.
What are instance variables and how do they relate to each instance of a class?
-Instance variables contain data that is unique to each instance of a class. They store the specific attributes of each object that is created from the class blueprint.
How is the 'init' method in a class used?
-The 'init' method is a special method used to initialize the instance variables of a class when a new instance is created. It is automatically called with the instance as its first argument, which is conventionally named 'self'.
What is the purpose of methods in a class?
-Methods in a class are functions associated with the class that allow instances to perform actions or operations. They help to encapsulate behavior and promote code reusability.
How can you create a method within a class to display an employee's full name?
-You can create a method called 'full_name' within the class that concatenates the instance variables 'first' and 'last' to display the full name. The method should return this concatenated string.
Why is the 'self' argument important in class methods?
-The 'self' argument is crucial because it represents the instance of the class when the method is called. It allows the method to access and modify the instance's attributes and other methods associated with it.
What happens if the 'self' argument is omitted from a method definition?
-If the 'self' argument is omitted, Python will raise a TypeError when the method is called because it expects the instance as the first argument to properly access the instance's attributes and methods.
How do you call a class method using the class name?
-To call a class method using the class name, you prefix the method name with the class name and use parentheses, manually passing the instance as an argument, like 'Classname.MethodName(instance)'.
What is the advantage of using the 'init' method over manually setting instance variables?
-Using the 'init' method allows for automatic initialization of instance variables when creating new instances, reducing the amount of code and the likelihood of errors that come from manual assignment.
How can you ensure that your class methods are reusable and less prone to mistakes?
-By encapsulating common behaviors and actions within methods, you reduce the need for repeating code and manual variable assignments, thus minimizing errors and making the code more maintainable and reusable.
Outlines
📚 Introduction to Classes in Python
This paragraph introduces the concept of classes in Python, explaining their purpose and application within the language. It emphasizes the importance of classes in modern programming for logically grouping data and functions, which facilitates code reusability and extensibility. The video aims to cover the basics of creating and instantiating classes, inheritance, class and instance variables, static methods, class methods, and more, across several videos. The use of classes is not only specific to Python but is a common feature in most modern programming languages. The paragraph also discusses the definition of attributes and methods associated with a class and presents a use case for classes in representing employees in a company's application.
🚀 Creating and Using the init Method
This section delves into the specifics of creating a class and its instances, with a focus on the special init method. The init method is introduced as a way to automatically set up attributes when creating new instances of a class, eliminating the need for manual attribute assignment. The paragraph explains how the init method receives the instance as the first argument (by convention named 'self') and any additional arguments specified. It demonstrates how to set instance variables using the init method and how this approach streamlines the process of creating new objects. The paragraph also highlights the importance of the 'self' argument in methods and how it allows methods to access the instance's attributes and perform actions on them.
🛠️ Adding Functionality with Class Methods
This paragraph discusses the addition of methods to a class to provide functionality to its instances. It illustrates how to create a method within a class to display an employee's full name, which is a common operation that can be efficiently centralized within the class. The section clarifies the syntax and structure of defining a method within a class and how it utilizes the 'self' argument to access the instance's attributes. It also addresses a common mistake of omitting the 'self' argument, which results in a TypeError, and explains the importance of this argument for the method to function correctly with all instances. The paragraph concludes with a comparison of calling a method on an instance versus calling it on the class itself, reinforcing the concept of 'self' as a reference to the instance.
Mindmap
Keywords
💡Classes
💡Instantiating
💡Inheritance
💡Class Variables
💡Instance Variables
💡Methods
💡Attributes
💡Static Methods
💡Class Methods
💡Constructor (init method)
💡Self
Highlights
Introduction to creating and using classes in Python and object-oriented programming concepts.
Explanation of why classes are important for logically grouping data and functions for easy reuse and expansion.
The distinction between a class and an instance of a class, with a class serving as a blueprint for creating unique instances.
Demonstration of creating a simple 'Employee' class and the concept of instance variables containing unique data for each instance.
Use of the special `__init__` method as a way to initialize instance variables automatically when creating new instances of a class.
Explanation of the `self` parameter in methods and how it represents the instance, allowing for attribute access and method invocation.
Creation of an 'email' attribute dynamically using the instance's first and last name.
The importance of using the `__init__` method to avoid manual and error-prone attribute assignment for each instance.
How to add methods to a class, such as a 'full_name' method, to perform actions and avoid repetitive code.
The necessity of including the `self` argument in instance methods and the consequences of omitting it.
Invoking class methods using the class name and passing the instance as an argument, illustrating the underlying mechanics.
Summary of the core concepts covered in the video, including creating classes, understanding instances, initializing attributes, and creating methods.
预告 of future videos covering more advanced topics like class variables and their difference from instance variables.
Encouragement for viewers to ask questions and engage in the comment section for further clarification.
Call to action for viewers to support the tutorials through likes, shares, and Patreon contributions.
Transcripts
Hey, everybody. How's [it] going in this series of videos?
We'll be learning how to create and use classes within python and how object-oriented concepts are applied within the language now
There's a lot to cover when working with classes, so I'm going to break these up into several different videos
We'll cover the basics of creating and instantiating classes will learn about inheritance class and instance variables
static methods and class methods and Several other topics
So breaking these up in several videos will allow us to focus on specific topics in each video so in this video
We'll be learning the basics of creating and instantiating simple classes, but first
Why should we even use classes now this isn't just specific to
Python you can see classes being used throughout most modern programming languages, and there's a good reason for that
they allow us to
Logically group our data and functions in a way that's easy to [reuse] and also easy to build upon if need be
Now just a quick side note when I say data and functions that are associated with a specific class
We call those attributes and methods, and you'll hear me use those terms a lot throughout these videos, so when I say methods
I mean a function that is associated with a class
[so] let's go ahead and get started so say we had an application for our company
And we wanted to [represent] our employees and our python code now
This would be a great use case for a class because each individual employee is going to have specific
Attributes and methods so for example each employee is going to have a name and email address [a] pay and also
Actions that they can perform so it'd be nice if we had a class
That we could use as a blueprint to create each employee so that we didn't have to do this manually each time from scratch
So let's go ahead and create a simple employee class and see what that would look like so to create a class
It's just as easy as saying class employee now
I'm going to leave this empty for now, and if we just left it like this and we get an error
so if you ever have a class or a function [that] you want to leave empty for the time being then you can simply put
In a past statement and python will know that you just want to skip that for now
So now we have a simple employee class with no attributes or methods
And I wanted to stop here because I wanted to explain the difference between a class and an instance of a class
So our class is basically a blueprint for creating
Instances and each unique employee that we create using our employee class will be an instance of that class
so for example if I said employee 1 equals employee and
EmPLoyee 2
Equals employee then each of these are [going] to be their own unique instances of the employee class
so for example if I go ahead and print both of these out and
Copy and paste that
There and you can see that both of these are employee objects, and they're both unique
They both have different locations here in memory now
This is an important distinction because you'll hear me talk a lot about
instance variables and class variables and it's important to know the difference between those and I'll go more in depth into class variables in the
next video but for this video
We're going to be looking at instance variables so instance variables contain Data that is unique to each instance
Now we could manually create instance variables for each employee by doing something like this
So let's say we wanted employee 1 to have a first name and a last name so I could just do employee 1 not first
Equals Corey and then I could do employee last
is
equal to
Schaefer and I could also give it an email address, so I'll do employee 1 dot email equals
and I'll just do the first name with the last name at
Company comm and lastly let's go ahead and add a pay [onto] there too, so I'll do employee 1 not pay and we'll just do
50,000 there now let's give employee to
Some of these same attributes so for this one. I'll just do test
User and then I'll do test
User and I will make that
60,000 ok so now each of these instances have attributes that are unique to them
so if I print it out, let's say I could print out the employee [1] dot mail and
Also print out the employee to email
On it looks like whenever I gave these the instance variables
I forgot to make this employee to here so now let's run that so now you can see that that email
Was created for each employee?
[let's] say that we wanted to set all of this information for each employee
When they're created rather than doing all of this manually like we did here
So we wouldn't want to have to
Manually set these variables every time you can see it's a lot of code and it's also prone to mistakes
Just like I did whenever I forgot to change the [to] employee, [too]
So we don't get much benefit of using classes if we did it this way, so to make these
Set up automatically when we create the employee we're going to use a special init method
So now inside of our employee class I'm going to create this special init method
Now you can think of this method as initialize and if you're coming from another language
Then you can think of this as the constructor now when we create methods within a class they [receive] the instance as the first argument
Automatically and by convention. We should call the instance self now. You can call it
Whatever you want
But it's a good idea to stick to convention here and just use self
So after self we can specify what other arguments that we want to
Accept so let's go ahead and accept the first name the [last] name and the pay and I know that we had email, too
But we can create the email using the first name and the last name so now within our and Knit method
We're going to set all of these instance variables
So let's do self dot first equals first and now I'm just going to do this for the rest of them as well
So [I'm] going to do self dot pay or self dot last and self dot pay and for the email
I can do self dot email equals first plus
and then we'll put a dot between those and then last and then we'll add on to the end at
company comm
Okay, so whenever I say that self is the instance what I mean by [that] is that when we self dot first?
equals [two] first here
It's going to be the same thing as us saying down here that employee one dot first equals
[Korey] except now instead of doing this manually
It'll be done automatically when we create our employee objects
Now these don't need to be the same as our arguments so for example. I could make this
Self dot f name equals first, but I usually like to keep these similar if possible
So I'm going to go ahead and set that back [to] self dot first equals first, okay?
So now when we create our instances of our employee class right here now
we can pass in the values that we
specified in our anit method now our net method takes the instance which we call itself and the first name last name and
Pay as arguments, but when we create our employee down here the instance is passed automatically
So we can leave off self we only need to provide the names and the pay so we could create these by
Passing in first and we have to do this in order
So I will pass in all of the same information that we did manually down there and for the second one
I'll do [test] and
User and I think I had that at
[sixty] [thousand] okay
so what would happen on this line when we create this employee the anit method will [be] run automatically, so
Employee one will be passed in as self and then it will set all [of] these attributes
So it'll set employee one dot first is equal to first which we passed in as quarry
Employee one that last equals what we passed in is last and so on so now that we have that an it method in place
We can go [ahead] and delete these manual assignments that we made down here
And you can see by deleting that that we got rid of a lot of code
So I'm going to go ahead and comment out those lines
[we're] printing [the] employees, and I'm just going [to] go ahead and print out the email
So if I run that then you can see that that still works, okay?
So everything that we have so far [like] the names and email and the pay are all attributes of our class now
Let's say that we wanted the ability to perform some kind of action not to do that
We can add some methods to our class
So let's say [that] I wanted the ability to display the full name of an employee now
This is an action that you'd likely need to do a lot with a class like this
So we can do this manually outside the class if I was to come down here and do
Print and I could get the full name just by putting in two
placeholders there and doing a format and saying employee one dot first and
Employee one dot last and if I go ahead and print this out
And you can see that we got the full name there
But that's a lot to type in each time that you want to display the employees full name, [so] instead
Let's create a method within our class that allows us to put this functionality in one place, so within our class here
I'm going to create a method called full name and we can do that with just doing a death of
Full name now [like] I said before each method within a class
Automatically takes the instance as the first argument
and
We're going to always call [that] self and the instance is the only argument that we'll need in order to get the full name
So within this method here
I'm just going [to] take the same logic that we had down here and cut that out
and I'm just going to go ahead and return that but we have to be careful here because
now instead of printing Employee [1]
[first-name] and [lastname], [I'm] going to use self so that it will work [with] all instances
So I'm going to do self dot first and self dot last
So now that we created that method instead of printing like we did before now
I can just come down [here] and do employee 1 dot full name and
Print that out
And if I run that then you can see that we got the same [thing] and notice that we need the parentheses here
Because this is a method instead of an attribute
So if I left the parentheses off and printed this then you can see that it prints the method instead
[of] the return value of the
method so we're going to have to put those parentheses on in order to run that properly so now we have full advantage of
Code reviews here, so instead of typing this out for each full name that I want to print now
I can just use that method so now if I wanted to print employee two's full name
It's just as easy as replacing employee one with employee two and running that and we get the correct answer
Okay, and one more quick thing that I wanted [to] point out here
Now one common mistake that I see when creating methods is forgetting the self argument for the instance
So let's take a quick look at what that would look like if we left that off
so now before I run this if I just comment it out this printing of full name down here and
Ran this then you can see I'm actually going to remove these print statements here as well
Now [you] can see that this runs without any errors
But if I was to try to run this method that we accidentally left self off of then
Run this and you can see that we get an error and the error that we got was a type error
full-name takes zero positional arguments
But one was given now this can be confusing because it doesn't look like we're passing any arguments here into full name
But the instance which in this case is employee two is getting passed automatically
So we have to expect that instance argument in our method, and that's why we added self
so I'm going to come back up [here] to full name and
Put self back in and now running this you can see that [it] runs
Correctly now we can also run these methods using the class name
Itself which makes it a bit more obvious of what's going on in the background because whenever we do that, so I'll do employee
Dot full name now [when] we run it from the class we have to manually pass in the instance as an argument
So in this case
I'll pass in employee one so you can see how these are similar, but not exactly the same
So I'm going to put these side-by-side just so that we can compare them here
So these two lines here do the exact [same] thing, but here when I do employee one
Which is a instance and I call the method. I don't need to pass in self
It does it automatically and when we call the method on the class
And it doesn't know what?
instance that we want to run that method with so we do have to pass in the instance and that gets passed in as
self and if I go [ahead] and
Print this out and run it then you can see that it works
Just like if we were to print out the employee one dot full name
And I wanted to show you that because that's actually what's going on in the background
when we run employee one dot full name it gets transformed into this here employee dot full name and
Passes in employee one as self and that's why we have self for these methods, so I hope that makes sense to you
That's not extremely important to know when we're just getting started with working with classes
But we need to understand that [in] later videos once we start inheriting from other classes and things like that
So I figured it would be a good thing to go ahead, and show you that now okay?
So I think that's going to do it for this video in this video
We learned how to create simple classes the difference between a class and an instance of that class and we also learned how to initialize
class attributes and create methods now
We still have a lot to cover in future videos, and we'll be going over more advanced topics, so in the next video
We'll learn about class variables, and how they differ from instance variables that we saw here
But if you do have any [questions] with what we covered in this video
Then feel free to ask in the comment section [below] and I'll do my best to answer those
If you enjoy these tutorials and would like to support them then there are several ways you can do that
The easiest way is to simply like the video and give it a thumbs up and also
it's a huge help to share these videos with
Anyone who you [think] would find them useful and if you have the means you can contribute through patreon
And there's a link to that page in [its] scription section below be sure to subscribe for future videos and thank you all for [watching]
関連動画をさらに表示
Classes and Objects in Python | OOP in Python | Python for Beginners #lec85
Class Methods in Python | How to add Methods in Class | Python Tutorials for Beginners #lec87
OOP in Python | Object Oriented Programming | Python for Beginners #lec84
Learn Python OOP in under 20 Minutes
Class Objects & Constructors | Godot GDScript Tutorial | Ep 16
DAY 07 | PHP AND MYSQL | VI SEM | B.CA | CLASS AND OBJECTS IN PHP | L1
5.0 / 5 (0 votes)