Tuesday 15 September 2015

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



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

for str.split(line) i'm calling method on str class , passing line object, happens list total of strings, string object?

it seems more clear me should phone call split() method on line object.

i'm having problem understanding why both ways work.

first, you're right in case, it's more readable (and more pythonic, etc.) phone call line.split() str.split(line).

but there cases str.split useful? sure. imagine had list of lines, , wanted split of them. of these more readable:

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

because str.split function works on str, don't have create new function works on str pass around.

more generally, you're asking why python has "unbound methods".* partly it's because naturally fall out of design how methods work in python.** mainly, it's because they're handy passing around higher-order functions (and because of thought absolutely should usable value unless there's reason not allow it).

as the lastly part, understanding how both work, might little involved answer. can larn basics of how work in tutorial; more details, see how methods work, has links other useful information. quick summary:

line.split bound method—a callable object knows value pass self parameter when later phone call it. so, line.split() calls bound method no additional arguments, , line automatically gets passed self. str.split unbound method—basically function. so, str.split(line) explicitly passes line self.

* since 3.x, term "unbound method" has been downplayed, because really, unbound method same thing function.

** guido has explained few times; start 2009 blog post first-class everything.

python string oop

No comments:

Post a Comment