Placeholder Image

Subtitles section Play video

  • Classes are a fundamental tool in any respectable programming language. Think

  • of a class as a template for creating objects with related data and functions

  • that do interesting things with that data.

  • Python makes it easy to create and use classes. In fact, most other programming

  • languages are quite jealous of Python for its elegance and simplicity. Today, we

  • will show you how to use classes in Python, and we will do so in a classy way.

  • Suppose we are building a new social network called friendface, and our goal

  • is to gather as much personal information as possible about our users...

  • for reasons.

  • We will have a lot of data about each user, and will write many

  • functions using that data. To organize this effort, let's start by making a

  • class called user. In Python, you define a class by first writing the class keyword,

  • followed by the name of the class. It's recommended that you capitalize all the

  • words in the name of your class. Finally, type a colon and press Enter. For our

  • first example, we will make the simplest class possible. We will do absolutely nothing.

  • Type pass and press Enter. Pass is a way

  • to type a line that does nothing. This is necessary, because when defining a class

  • you need at least one line. Now that we have defined our class, we can use it to

  • create different users. To make a user, type in the name of the class, followed

  • by parentheses. This looks like you are calling a method...and you are, in a fashion.

  • We call user 1 an instance of the user class. You can also call user 1 an object.

  • To attach data to this object, you first type the name of the object, a dot, the

  • name of the variable, and then give it a value. Let's give user 1 a first name and

  • a last name. Since first_name and last_name are attached to an object, we

  • call them fields. They store data specific to user one. To see that the

  • data is in the user one object, let's print them. You access the data the same

  • way you assigned it. Type the name of the object, dot, then the name of the field.

  • Let's also print the last name.

  • Excellent.

  • By the way,

  • you should not capitalize the name of fields, and if you use more than one word

  • in the field name, separate the words by underscores.

  • This is a tradition in Python,

  • so to avoid uncomfortable stares from your peers,

  • I would recommend using this convention.

  • Here the name Dave Bowman is attached to the object user 1

  • To make this clear, let's create standalone

  • variables also called first_name and last_name. These values are not attached

  • to a user object. If we print these values, we get the name Arthur Clarke but

  • if you print the values attached to user 1, you get Dave Bowman. Even though we use

  • the same variable names the values are kept separate. With classes, there is no

  • limit to the number of objects you can make.

  • Let's make a second user called,

  • creatively, user 2. We will give this user the name Frank Poole. We use the exact

  • same field names as before, but this time the values are attached to user 2. To see

  • that Python keeps these three names separate we will print the three names.

  • So classes are used to make objects, and each object can have different values

  • for the same variable names. You can attach additional fields to the objects,

  • and they do not have to be strings. Let's suppose user 1 has an age of 37, an

  • integer. And for user 2, let's assign a value for his favorite book. We are now

  • in a situation where user 1 and user to have different fields attached to them.

  • The user 1 has an age. User 2 does not. User 2 has a favorite book, but user 1

  • does not. If you print the age for user 1, you can see the value is there. And if

  • you look at the type for age ,it is indeed an integer. Now look what happens

  • when we try to print the age for user 2, which we have not assigned. We get an

  • attribute error so please exercise caution. If you are not certain an object

  • has a specific field, you may experience an error. I know what you are thinking.

  • Why did we go through the trouble of creating a class, when we could have just

  • as easily stored the data in a dictionary?

  • We will now see the additional features of classes which allow them to transcend

  • a simple dictionary. By adding methods using object initialization, including

  • help text, we can turn our simple class into a data powerhouse.

  • The first feature we will add is an init method.

  • A function inside a class is called a method.

  • init is short for initialization and some languages call initialization methods

  • constructors. The name of this method is init with double underscores before and

  • after the method. This method is called every time you create a new instance of

  • the class. The first argument to this method is the word self, which is a

  • reference to the new object that is being created. You can add additional

  • arguments after self. We'll add full name and birthday arguments. The first thing

  • we will do is store these values to fields in the object. We do this by

  • typing self, dot, the field name, and then assign it a value. We'll store the full name

  • as a field called name, but we will store the value birthday in a field also

  • called birthday. Be careful here. This birthday is the value provided when you

  • create a user object, but THIS birthday is the field that stores the value. To

  • keep this example simple, we will assume the birthday is in year-month-day format.

  • We will now create a user and use the init method. Like before, you type in

  • the name of the class and parentheses. This time, we must provide two values,

  • because the anit method is expecting two values: first, the name, then the birthday.

  • You can test that these values are stored in the object by printing them.

  • The data is all there.

  • Let's add another feature to our class. In the init method,

  • let's break apart the name and extract the first and last names. We will call

  • the split method on the full name, and pass in a space. This will chop the name

  • into pieces by cutting whenever it encounters a space. The pieces will be

  • stored in an array. The first name will be the first string in the array, and the

  • last name will be the last string in the array, which we can access using index

  • minus 1. Notice that we attach the first name to self

  • but didn't do this with the last name. We'll see what happens as a result.

  • Let's create the user just as before, and then print the full name. first name last name

  • and birthday. Run.

  • We get an attribute error when we try to print the last name.

  • This is because we didn't attach last name to the object using self. What

  • happened is we assigned the value to the variable last_name ,which only exists

  • until the end of the method. This is a quick fix. Let's go back and attach

  • last_name to self. Now, if you run the code everything works as expected.

  • We can further improve this class by adding some help text. To do this, you type a

  • special string which we call a docstring.

  • This is a string inside triple quotes that you type right after the first line.

  • Now look what happens when you call the help function for this class.

  • Python displays a useful overview of the user class.

  • It displays the docstring as a summary, and it also shows

  • the arguments that are expected in the init method.

  • Even if you are writing code only for yourself,

  • it is a good habit to write a docstring. You may have to use a

  • class years after you wrote it. A few seconds of typing is worth hours of

  • sanity down the line. Also notice that the help call displays two additional

  • items: dict and weekref. We will discuss these in the next video on classes.

  • Let's add another method to the user class that will return the age of the user in years.

  • Like the init method, the first argument is self. And to showcase our

  • responsible nature, add a brief docstring.

  • We will compute the age using the user's birthday,

  • so this method does not require any additional parameters. Since

  • we will be working with states we need to import the date/time module. Let's

  • first get today's date. We shall assume it is May 12th, 2001 so that everyone who

  • tests this code will get the same answer. Next, let's convert the birthday string

  • into a date object. There is a way to do this in a single line, but for clarity we

  • will use a more direct method. In this example, we assume the birthday was a

  • string in year-month-day format. From this string, we can extract the year,

  • the month, and the day as integers. With these three integers ,we can create a

  • date object for the users birthday. If you compute the difference between today

  • and the birthday, you get a time delta object. The time delta object has a field

  • called days. Ignoring leap years, we can now compute the age in years by dividing

  • by 365. Finally, return the age as an integer. To test this method, create the

  • user once more. Then call the age method, and print the result. 30 years old. Notice

  • that you did not type self when calling the age method. The self keyword is only

  • used when writing a method. By the way, if you call the help function once more you

  • will see the summary now includes a description of the age method.

  • Classes:

  • powerful contraptions. They empower you to group together data

  • (which we call fields) and related functions (which we call methods) into a

  • kind of factory for creating many objects (which we call instances).

  • Socratica is somewhat like a class which creates instances of high quality videos.

  • Who sees our videos is determined by a mysterious black box called the YouTube

  • Algorithm. The best way to tell the YouTube Algorithm that our videos are

  • worthy of watches is to engage. Tell someone on friendface our video exists

  • and that it's in a class by itself.

Classes are a fundamental tool in any respectable programming language. Think

Subtitles and vocabulary

Click the word to look it up Click the word to find further inforamtion about it