简体   繁体   中英

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

A is more readable.

So, 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM