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

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


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.

100 thoughts on “Python Classes and Objects || Python Tutorial || Learn Python Programming”

  1. I enjoyed this video. Using split on people's names can have some "fun" results "Leonardo da Vinci" (I know that 'da Vinci' wasn't his last name, its just an example of a European name with da/de/du that, in some cases belong as part of that last_name/family_name along with the space!)

  2. Ok am I the only one how come from C++, JAVA, C#, etc , and was like " but, you didn't define first_name and last_name in your class!🤨 "

  3. the series are pretty good, clean and clear but i see no use in that fancy interface, maybe it would be better to have just a white background, like in the matrix. :V tanks for share.

  4. william laroche

    I couldn't understand how to create objects in classes or what i could use them for, but now i get it. Thank you.

  5. mam! will you make a video on tips to learn programming, without taking admission for any collages or institutes.

  6. if you are about to make a class, ask yourself: does it actually make sense to use a class for this? Think about why you are making a class and think about if it is really necessary. Don’t over-encapsulate.

  7. python is the second the worst 😀😀😀😀😀😀😀😀😀 C++ is the best, People leave Python and go learn C++. The sound of the girl is awesome, Could I rent your vice to make C++ Course 😍😍😍😍😍😍😍😍😏

  8. I used "HAL 0.009" and "Supercomputer."
    I love your videos, I'm learning Python faster than I've learned any other coding language. This includes GWBASIC…
    I switched to Doctor Who and got it right, too.

  9. I have a question, why when i "print(user.age())" and going to AttributeError ? 'User' object has no attribute 'age' ?

  10. hello dear Socratica – overwhelming tutorial – very helpful. One question though can you put togehter the most important infos into a cheatsheet – a Summarizing Cheat Sheet to download would be fantastic.

    above all – keep up the great work. It rocks!

  11. Love your presentation but be careful with terminology. In Python, the split method returns a list not an array .

  12. Cynthia Cantrell

    Is it just me, or does the black box of the "mysterious YouTube Algorithm" look suspiciously like the black obelisks of "2001: A Space Odessy?"

  13. Damn… I'm smiling my ass off, cannot remove the grin… Great stylistic classy video, like a diamond in the rough. Thanks for coming up with this awesome series, I will definitely watch it all and recommend. Also – consider writing a Star Trek fan episode dedicated to Ulka, it just fits perfectly! Cheers

  14. We're glad you've found us! You can subscribe to Socratica here: http://bit.ly/SocraticaSubscribe

    To help us make videos faster, you can become our Patron! https://www.patreon.com/socratica

  15. file_file _cannotOpen1_1noSuchfile_

    1:12 you did not mention to add a [+tab] for pass. I get '"IndentationError: expected an indented block"', if not.

  16. Why, at 4:56, would you call a parameter an argument? What's the point of instilling all the terminology of fields and methods along with pep8 if you're going to call something by a different name. Might as well have stuck to calling them functions instead of methods.

  17. This is how knowledge should be spread.
    It feels professional, futuristic, fun and really soothing.
    Well structured and easy to understand. Great video 🙂

  18. Kanwar Programmer

    Help me. When a code

    import random

    rnum = (random.randint(1, 35))

    print(rnum)

    This happens.

    File "G:random.py", line 1, in <module>

    import random

    File "G:random.py", line 2, in <module>

    rnum = (random.randint(1, 35))

    AttributeError: module 'random' has no attribute 'randint'

  19. Thanks for the thoroughness and humor! you mentioned that " _weakref_" ( from the help function) will be described in an other video. Could you point out where ? thanks!

    4

  20. Bayonne Blasphemer

    0:19 Most other programming languages are jealous of Python? I don't think so. Programming languages are not sentient. Like most languages, it has its strengths and weaknesses. Having learned over 20 languages over the span of nearly 40 years, I say this with confidence. Python is excellent at some things, and horrible and cumbersome at others. If, nor the sake of argument, someone pointed a gun at my head and told me to choose one and only one language to use, it would be Perl, not Python. I'm not saying that Python is useless; far from that. As before, it excels at some things and is a less than optimal choice for others.

  21. Rohit Bhattiprolu

    When I tried the code, it kept on giving me the error that User () does not take any arguments. I'm using python 3.7.3 by the way.
    thanks

  22. Member information

    John 16: 31-33 "Do you now believe?" Jesus replied. "A time is coming and in fact has come when you will be scattered, each to your own home. You will leave me all alone. Yet I am not alone, for my Father is with me. "I have told you these things, so that in me you may have peace. In this world you will have trouble. But take heart! I have overcome the world."

  23. Overall a very good primer on class creation. However I do have to nit pick…not so much on the class construction but on the actual data being fed to construct one Dave Bowman.

    He was not born on the ides of March 1971 (ie 3/15/1971) but rather 5/30/1970.

    Like you I am a flesh and blood console refactored into a digital format and as such due diligence is necessary.

    Source: https://2001.fandom.com/wiki/David_Bowman

    Now would you like me to sing you a song?

    Daisy, Daisy give me…

    GENERAL FAULT ERROR….SYSTEM HALTED

  24. Why Python? We have BASIC an interpreter language from the 80’s. What about Object REXX? What’s wrong with Java ? And there already C++ …..

  25. Nice video. But it demonstrate the what and how, but do explain the context in which classes & object makes most of sense in the first place … and why …
    For my believe it is all about access control of data and therefore its protection from unintended (external) accesses to data, which gets localized into instances. And it makes complex software architecture(s) more testable …

  26. Since Socratica is a Python she bit Alexa, Cortana and Siri in the ass and fed them her poison in the hopes that they would learn something useful.

Leave a Reply

Your email address will not be published. Required fields are marked *