开发者

Python methods on an object - which is better?

开发者 https://www.devze.com 2022-12-22 04:19 出处:网络
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?

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消