Tuom L.
Tuom L.

Reputation: 182

Instance method or not

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

Upvotes: 1

Views: 70

Answers (2)

Alfe
Alfe

Reputation: 59416

Bar2 is clearly a hack (probably to reduce source length and maybe to reduce call overhead). I would not do this.

Reasons:

Bar2().bar is a method of Foo (which is surprising and thus no good style). You can check this yourself by having a look at Bar2().bar.im_self.

② Overriding the method of Bar2 is not possible for subclasses. You disable a valuable feature of classes this way.

③ Changing the Bar's foo later will only have the expected effect in Bar1 while in Bar2 the pointer to the method of the original foo will still be in use.

Upvotes: 2

fjarri
fjarri

Reputation: 9726

Should I make it clear that it is indeed a "method" (Bar1)

You should try not to expose the implementation of Bar to the user. Why would he care if it calls a method of some internal class? What's important is how the external API call behaves.

If you make it a method, it will imply that:

  • It changes the internal state of the object, or
  • It requires re-calculation on each call (just a silly example, if it represents the amount of time since the creation of the object), or
  • It takes a (relatively) significant amount of time to execute and cannot be cached.

Neither seems to be applicable in your case (of course, you have more information, since you actually know what bar() does, and how its behavior may change in the future).

Upvotes: 0

Related Questions