Home Forums Main Forums Python Forum Functions vs. Methods in Python

  • Functions vs. Methods in Python

     Datura updated 3 years, 4 months ago 1 Member · 1 Post
  • Datura

    Member
    December 15, 2020 at 11:33 am
    Up
    0
    Down

    Many Python beginners are confused about functions and methods in Python. Generally, speaking, they are very similar except for the features and uses.

    Functions are universal or global which can be applied to any object such as lists, tuples, sets, dicts, series and data frames. For example, print(), type(), len() are global functions and can be used with any data objects. When using functions, we use funct(x), where x is a data object. Below give some examples.

    x=[1, 3, 'Maths', 36.7]
    print(x)
    type(x)
    len(x)

    ### given df is a data frame
    print(df)
    type(df)
    len(df)

    In contrast, methods are local and attached to a specific object. A method in python is somewhat similar to a function, except it is associated with objects/classes. Methods in python are very similar to functions except for two major differences:

    1. The method is implicitly used for an object for which it is called.

    2. The method is accessible to data that is contained within the class.

    For example, head()/tail()/describe() are methods for Series and data frames. If you apply them to lists, sets, tuples etc, you will get errors. We need to use methods in this way: object.method() .

    ### given df is a data frame
    df.head()
    df.tail()
    df.describe()

    Given below list y, if we want to convert its elements to upper cases:

    y=['Auto', 'Bankcard', 'Demand', 'LOC', 'Mortgage']  # y is a list. 
    y.str.upper()
    AttributeError, 'list' object has no attribute 'str'

    ### Note: str() is a method associated with a Series rather than a list, we have to convert a list to a Series(vector) first. Similarly, upper() is a method associated with str() class, therefore we need to use str() before it.

    ### correct approach
    pd.Series(y).str.upper()
    • This discussion was modified 3 years, 4 months ago by  Datura.
    • This discussion was modified 3 years, 4 months ago by  Datura.
    • This discussion was modified 3 years, 4 months ago by  Datura.

Log in to reply.

Original Post
0 of 0 posts June 2018
Now