简体   繁体   中英

Python Method of method calls?

Today I am reading " Data Wrangling with Python " by Kazil & Jarumul ( Link ). It's my first week coding in Python.

In the text, we have a snippet of code on page 53 that looks like the following:

import json

json_data = open('Book Source Files/data/chp3/data-text.json').read() **#<< Focus Line**

data = json.loads(json_data) #json object, loads method?

for item in data:
    print('item', item)

I'm having a hard time understanding the focus line (2nd code line) above.

I know that Python seems to follow the general syntax of object.method(Inputs) when calling object methods. I also learned that I can call help without parenthesis when I have questions on objects or methods:

help(open.read) #errors. Incorrect.

But in this case, it almost looks like two methods are being called: open().read().

I tried looking for help on this method to explain this, but it seems like I am missing a core concept here. Is this some sort of shorthand? What is this known as, and in what circumstances is it used?

Follow up question: Sometimes We pass in many different values to a function. For example:

print('this','is','a','line','of','text')

How come some methods seem to have rules around what items are supplied, but other methods have a variable number of things that can be supplied when a method is called?

It is called Method Chaining

open() returns a object, you then call the read() method of that object.

Equivalent to:

fd = open(path)
data = fd.read()

Chaining can reduce readability for people who are not familiar with the function (like yourself.)

Regarding your question about "How come some methods seem to have rules around what items are supplied", it entirely depends on how that function is declared. You can decalre functions to accept any combination of no args, named args, keyword args.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM