vendredi 19 novembre 2021

Using a classmethod to wrap class functions, but not as an alternate constructor

I've gotten in the habit of using classmethods to wrap class functions rather than as an alternate constructor. It seems great to keep all relevant functions within the class namespace rather than defining a wrapper function in the general namespace. I've been told this is unpythonic and I haven't seen this pattern elsewhere. Why is pattern B preferable to pattern A?

Trivial examples:

Pattern A (my pattern):

class Foo():
  def __init__(self, bar):
    self.bar = bar

  def baz(self):
    print(self.bar)

  @classmethod
  def foobaz(cls, bar):
    foo = cls(bar)
    foo.baz()

Pattern B (a normal pattern):

class Foo():
  def __init__(self, bar):
    self.bar = bar

  def baz(self):
    print(self.bar)

def foobaz(bar):
    foo = Foo(bar)
    foo.baz()

Aucun commentaire:

Enregistrer un commentaire