0

How can I define a static class member with the type of this same class it is in? I intuitively tried it like this:

class A:
  def __init__(self,a,b,c,d):
    ...
  default_element = A(1,2,3,4)

Which gives the error

name 'A' is not defined

It would make the code for setting/resetting short and organized. There are workarounds such as

class A:
  def __init__(self,a=1,b=2,c=3,d=4):
    ...

or

class A:
  def __init__(self,a,b,c,d):
    ...

  @staticmethod
  def getDefault():
    return A(1,2,3,4)

but I would prefer the default element if possible, so we actually have an object representing the default, instead of a method and you can only have one set of default values, while with the prefered option I could have multiple different template-objects.

I'm on Python 3.6.9.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
nonsence90
  • 21
  • 4

1 Answers1

0

As far as I understand, this is not easily possible: (see "One Gotcha to be Aware of" in https://stackoverflow.com/a/27568860/1256837)

But there is a slight workaround and I focus on your requirement to provide different templates:

class _A:

    def __init__(self, a=None):
        self.a = a

    def blubb(self):
        return self.a**2

class A(_A):
    template_default = _A(0)
    template_1 = _A(5)

assert A.template_default.blubb() == 0
assert A.template_1.blubb() == 25
assert A(50).blubb() == 2500

However, I think this code smells: I don't think that this is a good practice.

But If you were to put this class in a python module ... then in your definition you can create module wide "constants" that would match different instantiations of your class. That, I suppose, would be a better approach.

Drey
  • 3,314
  • 2
  • 21
  • 26