简体   繁体   中英

Why does it make sense to write str.split(line) over line.split()?

For str.split(line) I'm calling a method on the str class and passing a line object, which happens to be a list full of strings, to the string object?

It seems more clear to me that I should just call the split() method on my line object.

I'm having trouble understanding why both ways work.

First, you're right that in this case, it's more readable (and more Pythonic, etc.) to just call line.split() than str.split(line) .

But are there any cases where str.split is useful? Sure. Imagine that you had a list of lines, and you wanted to split all of them. Which of these is more readable:

split_lines = map(str.split, lines)
split_lines = map(lambda line: line.split(), lines)

Because str.split is already a function that works on any str , you don't have to create a new function that works on any str to pass around.


More generally, what you're asking is why Python has "unbound methods".* Partly it's because they just naturally fall out of the design for how methods work in Python.** But mainly, it's because they're handy for passing around to higher-order functions (and because of the idea that absolutely everything should be usable as a value unless there's a good reason not to allow it).


As for the the last part, understanding how they both work, that might be a little involved for an SO answer. You can learn the basics of how they work in the tutorial ; for more details, see How methods work , which has links to other useful information. But as a quick summary:

  • line.split is a bound method—a callable object that knows what value to pass as the self parameter when you later call it. So, line.split() just calls that bound method with no additional arguments, and line automatically gets passed as the self .
  • str.split is an unbound method—basically just a function. So, str.split(line) explicitly passes line as the self .

* Since 3.x, the term "unbound method" has been downplayed, because really, an unbound method is the same thing as a function.

** Guido has explained this a few times; start with his 2009 blog post First-Class Everything .

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