-1

So say I have a Class:

class Testclass:
      def __init__(self, key)
          self.key = key


          def function(self, key):
              do something ... 

can I call specifically the function without calling the whole __init__ somewhere down the line inside a Testclass Method?

I need this because I have two functions within __init__ and I need them separately.

Or maybe I am doing this all wrong from the get go, so any other suggestions would be welcome.

Leonardo
  • 160
  • 2
  • 3
  • 13
  • You cant. Its a function scoped function and only available inside it. If you need them outside, declare them as member functions of the class. – Patrick Artner May 08 '20 at 11:22
  • @Torxed well I tried and got AttributeError that there is no attribute "function" my original issue is that I need to have a random list in Max-Heap state after initialisation so I wrote heapify and buildHeap functions inside __init__ but I need to call them later in a HeapSort Method. and yea it an assignment – Leonardo May 08 '20 at 11:29

1 Answers1

1

No you cannot, because those functions are local to __init__. Why don't you make them methods of the class?

class Testclass:
  def __init__(self, key)
      self.key = key
      result = self.function(key)

  def function(self, key):
      do something ... 
BlackBear
  • 22,411
  • 10
  • 48
  • 86
  • see my comment above why I can not write as Methods. I need something achieved right in the __init__ – Leonardo May 08 '20 at 11:31
  • @Leonardo you can call that function from within init (see my edit) – BlackBear May 08 '20 at 11:36
  • that was my first instinct and I tried it, but I was getting the error that function is not defined or something along those lines, I may have made syntax errors though... let me try that again. – Leonardo May 08 '20 at 11:37
  • yep that worked, I must have messed up something with self's before... I just started OOP... TY – Leonardo May 08 '20 at 11:42
  • @Leonardo no worries! Have fun :) – BlackBear May 08 '20 at 11:43
  • Am I stupid if I bring up the fact that you can create non-instance-classes? `class TestClass: def function(key): ...` and access it with `TestClass.function()` without an instance? – Torxed May 08 '20 at 13:57