Phil
Phil

Reputation: 3736

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()

Upvotes: 0

Views: 154

Answers (3)

phkahler
phkahler

Reputation: 5767

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.

Upvotes: 1

Amarghosh
Amarghosh

Reputation: 59451

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.

Upvotes: 2

brettkelly
brettkelly

Reputation: 28205

A is more readable.

So, A :)

Upvotes: 2

Related Questions