-1

Sorry for a bad explanation in advance - I have searched for a solution for my issue but have not found one. Basically, I am trying to define a class with an init that only gets called if no function within the class is called. For example:

 class ThisClass():
      def __init__(self):
           print "hello"

      def otherFunc(self):
           print "yeet"

If I call ThisClass() I would like it to print "hello", but if I call ThisClass().otherFunc() I would like to print "yeet" but NOT print "hello". Anyone know how to help? Again, sorry for a bad explanation but I wasn't sure how to make it better.

  • You describe a very strange use of classes usually you create instances, e.g. `a = ThisClass()` will call `ThisClass.__init__()` and will print `hello`, Then `a.otherFunc()` will only print `yeet` – AChampion Apr 20 '18 at 15:10
  • 7
    That's not possible, and even if it was, it would be bad design. This looks like an [XY Problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). What is the X you're trying to solve? – Aran-Fey Apr 20 '18 at 15:11
  • 1
    Yeah, no, just don't. At the very least this would be unexpected and surprising behaviour and the source of many bugs. – deceze Apr 20 '18 at 15:13
  • You can create a [static method](https://stackoverflow.com/questions/136097/what-is-the-difference-between-staticmethod-and-classmethod-in-python) to accomplish this. Then you can call `ThisClass.otherFunc()`. – Sunny Patel Apr 20 '18 at 15:15

1 Answers1

1

You can use static method or class method:

 class ThisClass():
      def __init__(self):
           print "hello"

      @staticmethod  # or @classmethod with `cls` as argument.
      def otherFunc():
           print "yeet"

ThisClass()  # hello
ThisClass.otherFunc() # yeet

EDIT: You could use a singleton or class variable if you want to absolutly call the __init__ in your class, but this is probably the wrong answer to the wrong question. Like @Aren-Fey said, this look like a XY problem!

TwistedSim
  • 1,960
  • 9
  • 23
  • Doesn't really fulfil the requirement as stated, no? – deceze Apr 20 '18 at 15:19
  • I use this statement:`If I call ThisClass() I would like it to print "hello", but if I call ThisClass().otherFunc() I would like to print "yeet" but NOT print "hello". ` – TwistedSim Apr 20 '18 at 15:22
  • Yeaaaahhhh… but you're not enabling calling of `ThisClass().otherFunc()`… – deceze Apr 20 '18 at 15:23
  • Question is a bit ill posed, so the answer will be approximate. I don't think he want to absolutly use a call to `__init__`. – TwistedSim Apr 20 '18 at 15:25
  • 1
    It is possible, but like you said, it's a XY problem, it will be better to don't have the answer to this :) (class variable, singleton pattern, metaclass, etc.) – TwistedSim Apr 20 '18 at 15:28
  • This works for the most part. There are still a few things to fix but I'm sure I can get them working. Thanks! – Harrison Sills Apr 20 '18 at 18:17