Python methods and function

Python Methods, Functions, & Libraries

Starting here? This lesson is part of a full-length tutorial in using Python for Data Analysis. Check out the beginning.

In this lesson, you’ll learn about:

  • Methods of dictionaries, specifically .keys() and .values()
  • Functions, specifically print, type(), and len()
  • Importing libraries with import

Using Mode Python notebooks

Mode is an analytics platform that brings together a SQL editor, Python notebook, and data visualization builder. Throughout this tutorial, you can use Mode for free to practice writing and running Python code.

  1. Log into Mode or create an account.
  2. Navigate to this report and click ‘Duplicate’. This will take you to the SQL Query Editor.
  3. Click ‘Python Notebook’ under ‘Notebook’ in the left navigation panel. This will open a new notebook.

Now you’re all ready to go.

Let’s use a dictionary you created in the previous lesson:

For a quick refresher of dictionaries, click here.

Say you want to see all the keys in the dictionary (in this case, cities). You can use a method called .keys() to get a list of the dictionary’s keys. A method is an action that you can take on an object. If a real-world window was an object, its methods might be .open() or .close() .

In this case, the object is the dictionary, and the action is to return the .keys() :

 ['New York City', 'San Francisco', 'Los Angeles', 'Tokyo'] 

Remember how everything in Python is an object? That output is a list object! You can double-check this using type() as in the previous lesson.

To further illustrate this, you can get the third item in the list of keys by referencing its index:

You can also get the values of the dictionary using the values() method:

 [8400000, 1837442, 18550000, 13350000] 

Practice Problem

To reiterate what you learned last lesson, get the population for Los Angeles.

 city_population['Los Angeles'] 

Using methods on combined objects

You can use methods on combined objects as well.

In the last lesson, you created a dictionary of lists by nesting individual lists of cities and their municipalities in a dictionary object. Here it is again:

As a reminder, to get a single municipality, you would enter the dictionary’s variable name— municipalities —and the list index— [‘Tokyo’][3] .

The keys of the dictionary are:

The values associated with the keys in that dictionary are:

 [['Manhattan', 'The Bronx', 'Brooklyn', 'Queens', 'Staten Island'], ['Akihabara', 'Harajuku', 'Shimokitazawa', 'Nakameguro', 'Shibuya', 'Ebisu/Daikanyama', 'Shibuya District', 'Aoyama', 'Asakusa/Ueno', 'Bunkyo District', 'Ginza', 'Ikebukuro', 'Koto District', 'Meguro District', 'Minato District', 'Roppongi', 'Shinagawa District', 'Shinjuku', 'Shinjuku District', 'Sumida District', 'Tsukiji', 'Tsukishima']] 

Remember that lists are denoted with square brackets? Notice that there are three sets of [] in the output. That’s because the .values() output is a list containing New York’s municipalities and Tokyo’s municipalities, both of which are lists, as well.

In other words, municipalities.values() is a list containing two lists.

So far, you’ve learned about objects and methods. Now it’s time to look at a few functions. They’re very similar to methods in that they perform an action, but unlike methods, functions are not tied to specific objects. To relate this concept to our earlier window example, the function throw_rock() could be used with a real-world object window , but also with vase or cow or a number of other objects.

Functions typically go in front of an object name (with the object wrapped in parentheses), whereas a method is appended to the end of an object name. For example, compare throw_rock(window) with window.open().

You’ve already used a function— type() —several times in this tutorial. It can be used on any object. Try it out here using different items within the municipalities object:

 print type(municipalities) print type(municipalities['Tokyo']) print type(municipalities['Tokyo'][0]) 

In the output above, ‘dict’ stands for dictionary, ‘list’ stands for list, and ‘str’ stands for string. In other words, municipalities is a dictionary, municipalities[‘Tokyo’] is a list, and municipalities[‘Tokyo’][0] is a string.

You may have noticed that we used the print function for every line of code (yes, print is a function! It can also be written as print(«object») ). If you want more than one line to print output, you need to insert print at the beginning of each line. This is because, by default, Python will only print the output associated with your last line of code in the cell. You can see this in action by removing the print part of the statements above:

 type(municipalities) type(municipalities['Tokyo']) type(municipalities['Tokyo'][0]) 

Practice Problem

What type are the values of city_population ?

Make sure you look at the answer to this problem, as it contains important concepts.

One way to get the answer would be to use a key that you already know like ‘New York City’ . Remember that this will actually return the type of the value associated wiht the key ‘New York City’ :

 type(city_population['New York City']) 

Another way to get the answer would be to get an item from the list of values:

 type(city_population.values()[0]) 

The resulting type, int , means integer, or a number without decimal places. You’ll learn more about integers in a later lesson.

You should also take a minute to understand how Python is evaluating the second answer. Everything is executed from the inside out, similar to the order of operations in math (remember PEMDAS?). Here’s the order in which Python runs the above line of code:

It looks like Tokyo has a large number of administrative districts. How many exactly?

The len() function will describe how long an object is:

len() returns something different depending on the type of object for which you’re getting the length. For a list, it returns the number of items in the list, as demonstrated above.

For a string, len() returns the number of characters in the string (including spaces):

 print municipalities['Tokyo'][2] len(municipalities['Tokyo'][2]) 

Practice Problem

What is the «length» of municipalities? What does that mean?

The «length» of the dictionary is the number of key-value pairs that are stored in the dictionary. In this case, the length is 2.

A library is a bundle of code made to help you accomplish routine tasks more quickly. Seaborn, for example, allows you to create visualizations with as little as one line of code. Without such a library, you’d have to write a ton of code to take an object and render a chart. Python is a popular language for data analysis in part because it has extremely robust libraries for data manipulation, visualization, machine learning, and a host of other applications.

Libraries are usually maintained by groups of contributors and made available online to anyone who wants to use them. This kind of collaboratively maintained software is often referred to as open source.

You need to import a library in order to access the things in it (like its objects and methods). To import a library, you usually have to download the code to the computer where Python is running, and then import it. In Mode, a number of libraries are already available to import, so you don’t have to download anything. Let’s import NumPy, a library that is commonly used for mathematical methods:

 import numpy # name of the library 

Now that you have the list of values, you can take their mean (also known as the average) using a method called .mean() from the NumPy library. First, you’ll assign the list of population values— city_population.values() —a new variable name— population_values .

 population_values = city_population.values() population_values 
 [8400000, 1837442, 18550000, 13350000] 

As you can see, this produces the expected result—a perfect match if we just run city_population.values() on its own:

 [8400000, 1837442, 18550000, 13350000] 

It’s good practice to create variables that refer to objects you’ll need later. Naming things will help you keep track of your work and will make your code much more readable to others.

Now that population_values is stored, you can use the numpy.mean() method on population_values :

 numpy.mean(population_values) 

The mean value of the city populations is about 10.5 million.

In this lesson, you learned about:

  • Methods of dictionaries, specifically .keys() and .values()
  • Functions, specifically print , type() , and len()
  • Importing libraries with import

In the next lesson, you’ll learn how to work with a DataFrame (a powerful tabular data structure from the pandas library) to view and process data.

Creating Pandas DataFrames & Selecting Data

Источник

Python Methods vs Functions — What’s the Difference?

The key difference between a function and a method in Python is:

  1. A function is implemented outside of a class. It does not belong to an object.
  2. A method is implemented inside of a class. It belongs to an object.

Calling a function on an object looks like this:

And calling a method of an object looks like this:

Here is a simple illustration of this key difference:

Python function vs method

Let’s take a look at a table that summarizes the main differences between methods and functions in Python. Notice that most of these differences apply to other programming languages too.

Functions vs Methods in Python—A Comparison Table

Here is a comprehensive comparison table that compares the key differences between methods and functions in Python.

Methods Functions
A method lives in a class. A function lives outside classes.
A method is associated with a class object. A function is not associated with any objects.
You can only call a method on an object. Calling a method by its name only is not possible. You can call a function by only using its name.
A method operates on the data of the object it belongs to. A function operates on the data you give it as an argument.
A method is dependent on the object it belongs to. A function is an independent block of code in the program.
A method always requires ‘self‘ as the first argument. A function doesn’t take ‘self‘ as an argument.

Function vs Method Example in Python

Probably the most famous function in Python is the print() function. You can call it on any object to output the object as text in the console.

To print a string, for example, call print() function on a string.

This is a great example of calling a function on an object in Python.

To demonstrate methods next, let’s continue with the string data type.

The string type str has a ton of built-in methods. One of which is the upper() method that converts the string object into uppercase.

To convert a string into uppercase, call the upper() method of a string.

string = "Test" upper_string = string.upper()

This is a great example of calling a method on an object in Python.

Methods vs Functions: A Code Example

Here is a simple code example of a class with a method. Outside the class, there is a function with the same name.

Please read the code comments to understand what’s going on.

class Weight(): weight = 100 # Defining a method def to_pounds(self): return 2.205 * self.weight # Defining a function def to_pounds(kilos): return 2.205 * kilos # Calling a method on an object. w = Weight() pounds = w.to_pounds() # Calling a function on an object kilos = 100 pounds = to_pounds(kilos)

Conclusion

Today you learned what is the difference between a function and a method in Python.

  • A function does not belong to a class. It is implemented outside of a class.
  • A method belongs to a class and it can only be called on objects of that class. A method is implemented inside of a class.

An example of a function in Python is the print() function.

An example of a commonly used method in Python is the upper() method of a string.

Thanks for reading. I hope you find it useful.

Further Reading

Источник

Читайте также:  Phpstorm file watcher css
Оцените статью