views:

98

answers:

3

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()
+2  A: 

A is more readable.

So, A :)

inkedmn
+1  A: 

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.

Amarghosh
Could use an @staticmethod decorator instead of B? Seems like a better solution.
Phil
@Phil: better for what? yes, you could use `@staticmethod` if you need it. It's not clear whether you need it though.
SilentGhost
+1  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.

phkahler
The Python stdlib makes a point of returning None instead of self, when the point of a method has nothing to do with the return value, even when returning self would let you chain and type less. Case in point: `list.sort` . So, no. I don't really think you could call it pythonic, although what is or is not pythonic is hardly objective.
Devin Jeanpierre