YTread Logo
YTread Logo

Python Classes and Objects || Python Tutorial || Learn Python Programming

Jun 08, 2021
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 it with class. Let's say we're building a new social network called friendface, and our goal is to collect as much personal information as possible about our users... for reasons.
python classes and objects python tutorial learn python programming
We will have a lot of data about each user and we will write a lot of functions using that data. To organize this effort, let's start by creating a class called user. In Python, you define a class by first typing the class keyword, followed by the class name. It is recommended that you capitalize all words in your class name. Finally, type a colon and press Enter. For our first example, we will create the simplest class possible. We will do absolutely nothing. Type pass and press Enter. Passing is a way of writing a line that does nothing.
python classes and objects python tutorial learn python programming

More Interesting Facts About,

python classes and objects python tutorial learn python programming...

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 create a user, type the class name, followed by parentheses. It sounds like you're calling a method... and you are, in a way. 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 period, the name of the variable, and then assign a value to it. Let's give user 1 a first and last name.
python classes and objects python tutorial learn python programming
Since first and last name are attached to an object, we call them fields. They store user-specific data. To see that the data is in the user object, let's print it. Access data the same way you assigned it. Type the name of the object, the point, and then the name of the field. Let's also print the last name. Excellent. By the way, you should not capitalize field names, and if you use more than one word in the field name, separate the words with underscores. This is a tradition in Python, so to avoid awkward looks from your peers, I would recommend using this convention.
python classes and objects python tutorial learn python programming
Here the name Dave Bowman is attached to the user 1 object. To make this clear, let's create independent variables also called first 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 we print the values ​​attached to user 1, we get Dave Bowman. Although we use the same variable names, the values ​​are kept separate. With classes, there is no limit to the number of

objects

you can create. Let's make a second user called, creatively, user 2. We'll 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'll print all three names. So classes are used to create objects and each object can have different values ​​for the same variable names. You can attach additional fields to objects and they do not have to be strings. Suppose user 1 has an age of 37 years, an integer. And for user 2, let's assign a value to his favorite book. Now we are in a situation where user1 and user have different fields attached to them. 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 of user 1, you can see that the value is there.
And if you look at the age type, it's actually an integer. Now look what happens when we try to print the age of user 2, which we have not assigned to him. We got an attribute error, so be careful. If you are not sure that an object has a specific field, you may experience an error. I know what you're thinking. Why do we go to the trouble of creating a class, when we could have just as easily stored the data in a dictionary? Now we will look at the additional features of classes that allow them to transcend a simple dictionary.
By adding methods that use object initialization, including help text, we can turn our simple class into an inexhaustible source of data. The first feature we will add is a start method. A function within 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 being created.
You can add additional arguments after self. We will add full name and date of birth arguments. The first thing we will do is store these values ​​in the object fields. We do this by typing self, period, the name of the field and then assigning a value to it. We will store the full name as a field called name, but we will store the birthday value 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 simplify this example, we will assume that the birthday is in year-month-day format.
Now we will create a user and use the init method. As before, write the class name and the parentheses. This time, we need to provide two values, because the anit method expects two values: first, the name, then the birthday. You can test that these values ​​are stored in the object by printing them. All the data is there. Let's add another feature to our class. In the init method, let's separate the name and extract the first name and last name. We'll call the split method by the full name and pass in a space. This will chop the name into pieces every time it finds a space.
The parts 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 attached the first name to self but did not do this with the last name. We'll see what happens as a result. Let's create the user as before and then print the full name. first name, last name and date of birth. Run. We received an attribute error when we tried to print the last name. This is because we don't attach the last name to the object using self.
What happened is that we assigned the value to the variable lastname, which only exists until the end of the method. This is a quick fix. Let's go back and attach last name to ourselves. Now if you run the code everything works as expected. We can further improve this class by adding some help text. To do this, write a special string that we call the docstring. This is a triple-quoted string that is written right after the first line. Now look what happens when you call the helper function for this class. Python shows a useful overview of the User class.
Displays the docstring as a summary and also displays the arguments expected in the init method. Even if you write code just for yourself, it's a good habit to write a docstring. You may need to use a class years after you wrote it. A few seconds of typing is worth hours of sanity down the road. Also notice that the help call displays two additional elements: dict and Weekref. We will talk about this in the next video about classes. Let's add another method to the user class that will return the user's age in years. Like the init method, the first argument is self.
And to show our responsible nature, add a short documentation chain. We will calculate 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 get today's date first. We'll assume it's May 12, 2001 so everyone who tries this code gets the same answer. Next, let's convert the birthday string to 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 assumed that birthday was a string in year-month-day format.
From this string we can extract the year, month and day as integers. With these three integers, we can create a date object for the users birthday. If you calculate the difference between today and the birthday, you will get a time delta object. The time delta object has a field called days. Ignoring leap years, we can now calculate the age in years by dividing it by 365. Finally, it returns the age as an integer. To try this method, create the user once again. Then call the age method and print the result. 30 years. Notice that you didn't write self when calling the age method.
The self keyword is only used when writing a method. By the way, if you call the helper function one more time you'll see that the summary now includes a description of the old method. Classes: powerful gadgets. They allow you to group data (which we call fields) and related functions (which we call methods) into a kind of factory to create many objects (which we call instances). Socratica is something like a class that instantiates high-quality videos. Who watches 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 worth watching is to participate.
Tell someone on friendface that our video exists and is one of a kind.

If you have any copyright issue, please Contact