0

Im using a function I downloaded somewhere however its not a function but a class and I have no clue how to call it. This is aproximately how it looks, say this is examplefile.py:

class exampleclass:
  somevar = 1

  def func1(self, input):
    return input+somevar

  def func2(self, input):
    return input-somevar

def main():
  hardvar = 2
  examp = exampleclass()
  out1 = examp.func1(hardvar)
  out2 = examp.func2(hardvar)
  print(hardvar,out1,out2)

if __name__ == "__main__"
  main()

I just dont get how to use the functions inside of it. I tried

import examplefile
import exampleclass
from examplefile import exampleclass

some of these do import the class, then I try calling it like this

exampleclass.func1(1)

or

exampinstance= exampleclass
exampinstance.func1(1)

which both get me

TypeError: unbound method ...() must be called with ... instance as first argument (got list instance instead)

and thats what never works, I looked at several questions (such as these) here but I just dont get how it works. Maybe you guys can see what Im not getting.

Community
  • 1
  • 1
Leo
  • 1,757
  • 3
  • 20
  • 44
  • 1
    You are mixing up the difference between a module, i.e. a file, and the classes defined within the module. I.e. to use the example above do you must first import the module, declare an instance, and call its member functions. E.g. `import examplefile; ii=examplefile.exampleclass(); ii.func1(1)`. – Dov Grobgeld Dec 08 '14 at 20:53
  • Thanks, youre right I dont know the exact property differences between those. Ill look it up, especially the class link from daniels answer. – Leo Dec 08 '14 at 20:58

1 Answers1

1

I call you to look at the following link. It may help:

How to instantiate a class in python

However you are nearly there. The code would look something like:

exampinstance= exampleclass()
exampinstance.func1(1)

Note the () at the end of the first line. You need to instantiate the class properly. Note how the class is instantiated in the Main Method of the file itself.

Community
  • 1
  • 1
Daniel Casserly
  • 3,552
  • 2
  • 29
  • 60
  • Yup that was it. Thanks a bunch! Such a small mistake, I didnt see it though, thanks for pointing it out. – Leo Dec 08 '14 at 20:53
  • No worries. Don't forget to mark the answer as correct (with the tick) if this was correct. Thanks. – Daniel Casserly Dec 08 '14 at 20:54
  • Whats the benefit of having to make an instance before anyways? With packages you dont need to do that and they have the same functionality. – Leo Dec 08 '14 at 21:14
  • Erm, pass. I suppose it will make sense in some cases and not in others. To be honest I don't do an aweful lot of coding in python and wouldn't be able to point you int the best direction but I'm sure the docs will have answers – Daniel Casserly Dec 08 '14 at 21:31