Python Classes and Objects Python Tutorial Learn Python Programming

Python Classes and Objects  Python Tutorial  Learn Python Programming
Spread the love

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 we’ll 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 user1 an instance of the user    class    you can also call user1 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 one 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 user1    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 stairs from your    peers i would recommend using this    convention    here the name dave bowman is attached to    the object user1    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 clark    but if you print the values attached to    user one 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 two    we will give this user the name frank    pool    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 two let’s assign a value    for his favorite book    we are now in a situation where user one    and user two have different fields    attached to them    the user one has an age user two 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 store 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 init 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 one    notice that we attached 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    lastname to the object using self    what happened is 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    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 docs string 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 week ref    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 doctrine    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 dates we    need to import the date time module    let’s first get today’s date    we shall assume it is may 12    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 assumed 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 user’s 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 the 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 are 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 friend face our video    exists and that it’s in a class by    itself    you    


Leave a Reply

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