Python OOP Tutorial 1: Classes and Instances

Corey Schafer
20 Jun 201615:24

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

00:00

📚 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.

05:03

🚀 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.

10:04

🛠️ 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

Classes are a fundamental concept in object-oriented programming, providing a way to define a blueprint for creating objects. In the context of the video, classes allow for the logical grouping of data (attributes) and functions (methods), making it easier to reuse and build upon code. For example, the 'Employee' class is used as a blueprint to create individual employee objects with unique attributes and methods.

💡Instantiating

Instantiating refers to the process of creating an object from a class. It involves using the class definition to allocate memory for the object and assign it a unique identity. In the video, instantiating the 'Employee' class results in individual employee objects, each with their own set of attributes and methods.

💡Inheritance

Inheritance is a core concept in object-oriented programming that allows a class to derive properties and behavior from another class. It promotes code reusability and establishes a relationship between classes where one class can inherit attributes and methods from another. Although not deeply explored in this video, it is mentioned as a topic to be covered in future videos.

💡Class Variables

Class variables are attributes that are shared among all instances of a class. They are part of the class definition and can be accessed by all objects created from the class. Unlike instance variables, which contain data unique to each object, class variables hold data that is common to all instances.

💡Instance Variables

Instance variables are attributes that are unique to each object instance of a class. They contain data specific to the individual object and can differ from one instance to another. Instance variables are defined within the class but are assigned values when the object is created, allowing each object to maintain its own state and data.

💡Methods

Methods are functions that are associated with a class and are used to perform actions or operations on the data associated with the class. They are a way to define behavior within the class and can be called on any instance of the class. Methods are a key component of object-oriented programming, allowing objects to interact with each other and with the environment.

💡Attributes

Attributes are the characteristics or properties of an object that are associated with its class. They represent the data that an object holds, and can be accessed or modified through methods. Attributes are an essential part of object-oriented programming, allowing objects to store and manage information.

💡Static Methods

Static methods are methods within a class that do not require an instance of the class to be called. They are associated with the class itself rather than with any specific object instance. Static methods are often used for utility functions that do not depend on the object's state or instance variables.

💡Class Methods

Class methods are methods that are bound to the class rather than to its instances. They are declared with the '@classmethod' decorator in Python and are typically used to create or manipulate class variables or to add new instances to the class. Unlike static methods, class methods receive the class itself as their first argument, conventionally named 'cls'.

💡Constructor (init method)

The constructor, often referred to as the init method in Python, is a special method that is automatically called when a new instance of a class is created. It is used to initialize the instance variables of the object with the values provided during instantiation. This method is essential for setting up the object's state and preparing it for use.

💡Self

In object-oriented programming, 'self' is a reference to the current instance of the class and is used in class methods and instance variables to refer to the object itself. It is the first parameter of any method within a class and is used to access attributes and other methods of the instance. 'Self' is a convention in Python and is not a reserved keyword, but it is widely used and recommended for clarity and consistency.

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

play00:00

Hey, everybody. How's [it] going in this series of videos?

play00:02

We'll be learning how to create and use classes within python and how object-oriented concepts are applied within the language now

play00:09

There's a lot to cover when working with classes, so I'm going to break these up into several different videos

play00:13

We'll cover the basics of creating and instantiating classes will learn about inheritance class and instance variables

play00:19

static methods and class methods and Several other topics

play00:22

So breaking these up in several videos will allow us to focus on specific topics in each video so in this video

play00:29

We'll be learning the basics of creating and instantiating simple classes, but first

play00:34

Why should we even use classes now this isn't just specific to

play00:37

Python you can see classes being used throughout most modern programming languages, and there's a good reason for that

play00:43

they allow us to

play00:44

Logically group our data and functions in a way that's easy to [reuse] and also easy to build upon if need be

play00:51

Now just a quick side note when I say data and functions that are associated with a specific class

play00:56

We call those attributes and methods, and you'll hear me use those terms a lot throughout these videos, so when I say methods

play01:02

I mean a function that is associated with a class

play01:07

[so] let's go ahead and get started so say we had an application for our company

play01:11

And we wanted to [represent] our employees and our python code now

play01:15

This would be a great use case for a class because each individual employee is going to have specific

play01:20

Attributes and methods so for example each employee is going to have a name and email address [a] pay and also

play01:28

Actions that they can perform so it'd be nice if we had a class

play01:31

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

play01:38

So let's go ahead and create a simple employee class and see what that would look like so to create a class

play01:44

It's just as easy as saying class employee now

play01:48

I'm going to leave this empty for now, and if we just left it like this and we get an error

play01:52

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

play01:57

In a past statement and python will know that you just want to skip that for now

play02:02

So now we have a simple employee class with no attributes or methods

play02:06

And I wanted to stop here because I wanted to explain the difference between a class and an instance of a class

play02:13

So our class is basically a blueprint for creating

play02:17

Instances and each unique employee that we create using our employee class will be an instance of that class

play02:24

so for example if I said employee 1 equals employee and

play02:29

EmPLoyee 2

play02:31

Equals employee then each of these are [going] to be their own unique instances of the employee class

play02:38

so for example if I go ahead and print both of these out and

play02:45

Copy and paste that

play02:47

There and you can see that both of these are employee objects, and they're both unique

play02:53

They both have different locations here in memory now

play02:55

This is an important distinction because you'll hear me talk a lot about

play02:59

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

play03:06

next video but for this video

play03:08

We're going to be looking at instance variables so instance variables contain Data that is unique to each instance

play03:14

Now we could manually create instance variables for each employee by doing something like this

play03:20

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

play03:28

Equals Corey and then I could do employee last

play03:34

is

play03:36

equal to

play03:37

Schaefer and I could also give it an email address, so I'll do employee 1 dot email equals

play03:44

and I'll just do the first name with the last name at

play03:49

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

play03:57

50,000 there now let's give employee to

play04:01

Some of these same attributes so for this one. I'll just do test

play04:06

User and then I'll do test

play04:10

User and I will make that

play04:13

60,000 ok so now each of these instances have attributes that are unique to them

play04:19

so if I print it out, let's say I could print out the employee [1] dot mail and

play04:26

Also print out the employee to email

play04:31

On it looks like whenever I gave these the instance variables

play04:35

I forgot to make this employee to here so now let's run that so now you can see that that email

play04:40

Was created for each employee?

play04:43

[let's] say that we wanted to set all of this information for each employee

play04:46

When they're created rather than doing all of this manually like we did here

play04:51

So we wouldn't want to have to

play04:53

Manually set these variables every time you can see it's a lot of code and it's also prone to mistakes

play04:58

Just like I did whenever I forgot to change the [to] employee, [too]

play05:03

So we don't get much benefit of using classes if we did it this way, so to make these

play05:09

Set up automatically when we create the employee we're going to use a special init method

play05:14

So now inside of our employee class I'm going to create this special init method

play05:20

Now you can think of this method as initialize and if you're coming from another language

play05:25

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

play05:34

Automatically and by convention. We should call the instance self now. You can call it

play05:39

Whatever you want

play05:40

But it's a good idea to stick to convention here and just use self

play05:44

So after self we can specify what other arguments that we want to

play05:49

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

play05:56

But we can create the email using the first name and the last name so now within our and Knit method

play06:02

We're going to set all of these instance variables

play06:06

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

play06:14

So [I'm] going to do self dot pay or self dot last and self dot pay and for the email

play06:20

I can do self dot email equals first plus

play06:24

and then we'll put a dot between those and then last and then we'll add on to the end at

play06:32

company comm

play06:34

Okay, so whenever I say that self is the instance what I mean by [that] is that when we self dot first?

play06:42

equals [two] first here

play06:43

It's going to be the same thing as us saying down here that employee one dot first equals

play06:49

[Korey] except now instead of doing this manually

play06:53

It'll be done automatically when we create our employee objects

play06:57

Now these don't need to be the same as our arguments so for example. I could make this

play07:03

Self dot f name equals first, but I usually like to keep these similar if possible

play07:09

So I'm going to go ahead and set that back [to] self dot first equals first, okay?

play07:14

So now when we create our instances of our employee class right here now

play07:19

we can pass in the values that we

play07:21

specified in our anit method now our net method takes the instance which we call itself and the first name last name and

play07:28

Pay as arguments, but when we create our employee down here the instance is passed automatically

play07:36

So we can leave off self we only need to provide the names and the pay so we could create these by

play07:43

Passing in first and we have to do this in order

play07:46

So I will pass in all of the same information that we did manually down there and for the second one

play07:53

I'll do [test] and

play07:55

User and I think I had that at

play07:59

[sixty] [thousand] okay

play08:00

so what would happen on this line when we create this employee the anit method will [be] run automatically, so

play08:09

Employee one will be passed in as self and then it will set all [of] these attributes

play08:14

So it'll set employee one dot first is equal to first which we passed in as quarry

play08:21

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

play08:28

We can go [ahead] and delete these manual assignments that we made down here

play08:33

And you can see by deleting that that we got rid of a lot of code

play08:36

So I'm going to go ahead and comment out those lines

play08:39

[we're] printing [the] employees, and I'm just going [to] go ahead and print out the email

play08:43

So if I run that then you can see that that still works, okay?

play08:47

So everything that we have so far [like] the names and email and the pay are all attributes of our class now

play08:54

Let's say that we wanted the ability to perform some kind of action not to do that

play08:58

We can add some methods to our class

play09:00

So let's say [that] I wanted the ability to display the full name of an employee now

play09:05

This is an action that you'd likely need to do a lot with a class like this

play09:09

So we can do this manually outside the class if I was to come down here and do

play09:16

Print and I could get the full name just by putting in two

play09:20

placeholders there and doing a format and saying employee one dot first and

play09:27

Employee one dot last and if I go ahead and print this out

play09:33

And you can see that we got the full name there

play09:36

But that's a lot to type in each time that you want to display the employees full name, [so] instead

play09:42

Let's create a method within our class that allows us to put this functionality in one place, so within our class here

play09:49

I'm going to create a method called full name and we can do that with just doing a death of

play09:56

Full name now [like] I said before each method within a class

play10:01

Automatically takes the instance as the first argument

play10:03

and

play10:04

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

play10:12

So within this method here

play10:15

I'm just going [to] take the same logic that we had down here and cut that out

play10:20

and I'm just going to go ahead and return that but we have to be careful here because

play10:25

now instead of printing Employee [1]

play10:29

[first-name] and [lastname], [I'm] going to use self so that it will work [with] all instances

play10:35

So I'm going to do self dot first and self dot last

play10:38

So now that we created that method instead of printing like we did before now

play10:43

I can just come down [here] and do employee 1 dot full name and

play10:49

Print that out

play10:49

And if I run that then you can see that we got the same [thing] and notice that we need the parentheses here

play10:55

Because this is a method instead of an attribute

play10:58

So if I left the parentheses off and printed this then you can see that it prints the method instead

play11:05

[of] the return value of the

play11:07

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

play11:14

Code reviews here, so instead of typing this out for each full name that I want to print now

play11:19

I can just use that method so now if I wanted to print employee two's full name

play11:23

It's just as easy as replacing employee one with employee two and running that and we get the correct answer

play11:31

Okay, and one more quick thing that I wanted [to] point out here

play11:35

Now one common mistake that I see when creating methods is forgetting the self argument for the instance

play11:42

So let's take a quick look at what that would look like if we left that off

play11:46

so now before I run this if I just comment it out this printing of full name down here and

play11:52

Ran this then you can see I'm actually going to remove these print statements here as well

play11:57

Now [you] can see that this runs without any errors

play12:00

But if I was to try to run this method that we accidentally left self off of then

play12:06

Run this and you can see that we get an error and the error that we got was a type error

play12:12

full-name takes zero positional arguments

play12:15

But one was given now this can be confusing because it doesn't look like we're passing any arguments here into full name

play12:22

But the instance which in this case is employee two is getting passed automatically

play12:28

So we have to expect that instance argument in our method, and that's why we added self

play12:34

so I'm going to come back up [here] to full name and

play12:37

Put self back in and now running this you can see that [it] runs

play12:41

Correctly now we can also run these methods using the class name

play12:47

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

play12:56

Dot full name now [when] we run it from the class we have to manually pass in the instance as an argument

play13:04

So in this case

play13:04

I'll pass in employee one so you can see how these are similar, but not exactly the same

play13:10

So I'm going to put these side-by-side just so that we can compare them here

play13:14

So these two lines here do the exact [same] thing, but here when I do employee one

play13:20

Which is a instance and I call the method. I don't need to pass in self

play13:25

It does it automatically and when we call the method on the class

play13:30

And it doesn't know what?

play13:31

instance that we want to run that method with so we do have to pass in the instance and that gets passed in as

play13:37

self and if I go [ahead] and

play13:40

Print this out and run it then you can see that it works

play13:44

Just like if we were to print out the employee one dot full name

play13:48

And I wanted to show you that because that's actually what's going on in the background

play13:52

when we run employee one dot full name it gets transformed into this here employee dot full name and

play14:00

Passes in employee one as self and that's why we have self for these methods, so I hope that makes sense to you

play14:07

That's not extremely important to know when we're just getting started with working with classes

play14:12

But we need to understand that [in] later videos once we start inheriting from other classes and things like that

play14:18

So I figured it would be a good thing to go ahead, and show you that now okay?

play14:22

So I think that's going to do it for this video in this video

play14:25

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

play14:33

class attributes and create methods now

play14:36

We still have a lot to cover in future videos, and we'll be going over more advanced topics, so in the next video

play14:41

We'll learn about class variables, and how they differ from instance variables that we saw here

play14:46

But if you do have any [questions] with what we covered in this video

play14:49

Then feel free to ask in the comment section [below] and I'll do my best to answer those

play14:53

If you enjoy these tutorials and would like to support them then there are several ways you can do that

play14:57

The easiest way is to simply like the video and give it a thumbs up and also

play15:01

it's a huge help to share these videos with

play15:02

Anyone who you [think] would find them useful and if you have the means you can contribute through patreon

play15:07

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]

Rate This

5.0 / 5 (0 votes)

Related Tags
Python TutorialProgramming BasicsObject-OrientedCode LearningSoftware DevelopmentPython ClassesMethod DefinitionsInstance VariablesEmployee ManagementCode Efficiency