Consider the following example:
class Foo(object):
def bar(self):
return "bar"
class Bar1(object):
def __init__(self):
self.foo = Foo()
def bar(self):
return self.foo.bar()
class Bar2(object):
def __init__(self):
self.bar = Foo().bar
Bar1().bar() == Bar2().bar()
Which of Bar1 and Bar2 should one prefer? What are the pro/cons of the alternatives?
What I'm trying to ask is that there is an instance which has only one method, which is used in another instance. Should I make it clear that it is indeed a "method" (Bar1) or should I save one function call and some complexity (Bar2)?
Bar3().foo.bar()to make it clear that there is a different object involved. If Foo’sbaris completely unrelated to theBartype, it makes no sense to expose it as a Bar method instead.Bar, or is it something that acts on some attribute ofBar? Put it where it feels correct. In common with the answers below,Bar2seems odd to me. You're pretending a method onFoois a method onBar, but it's always bound to a particular instance ofFoo, so you're going to very much break expectations.