Python methods on an object - which is better?
Hopefully an easy question. If I have an object and I want to call a method on it which is the better approach, A or B?
class foo(object):
def bar():
print 'bar'
# approach A
f开发者_运维知识库 = foo()
f.bar()
# approach B
foo().bar()
If your sole intent is to call bar()
on a foo
object, B is okay.
But if you actually plan to do something with the object later, you must go with A as B doesn't leave you any references to the created object.
A is more readable.
So, A :)
Approach B doesn't keep the object around. If method bar() returns self then you can write:
f = foo().bar()
Personally I like method A. Though I've started making setter functions that return self in order to chain them together like above - I don't think other people consider that pythonic.
精彩评论