PEP8-compliant solution: formatting the line
实际上,PEP8 :
Long lines can be
broken over multiple lines by wrapping expressions in parentheses. These
should be used in preference to using a backslash for line continuation.
Make sure to indent the continued line appropriately.
因此,我赞成你的守则。
(
myOjbect
.doStuf()
.doMoreStuf()
.goRed()
.goBlue()
.die()
)
Alternative solutions: splitting into separate statements
依据《公约》第2条,在每种方法回归的数值方面,可以选择两种办法:
- Every method (maybe except
die()
, which is not required, as its result is not being used) returns modified instance (the same instance, on which it was called).
- Every method (still,
die()
is not required to do that) returns copy of the instance on which it was called.
Solution for mutable objects (methods return original instance)
In first case (when returning same instance), the solution to split longer lines into several statements is:
myObject.doStuf()
myObject.doMoreStuf()
myObject.goRed()
myObject.goBlue()
myObject.die()
真正的世界例子涉及 objects:
my_stuff = []
my_stuff.append( laptop ) # my_stuff == [ laptop ]
my_stuff.append( jacket ) # my_stuff == [ laptop , jacket ]
my_stuff.append( apple ) # my_stuff == [ laptop , jacket , apple ]
(虽然list.append()
is not Return any, only for行文一致 and forclar that it is mutable)
Solution for immutable objects (methods return modified copy)
在second case(在交回本时),类似的解决办法是:
myObject = myObject.doStuf()
myObject = myObject.doMoreStuf()
myObject = myObject.goRed()
myObject = myObject.goBlue()
myObject.die()
真正的世界例子涉及不可改变的物体:
name = -Tadek-
name = name.strip( - ) # name == Tadek
name = name.lower() # name == tadek
name = name.replace( k , ck ) # name == tadeck