11

How do i call an outside function from this class ?

def test(t):
   return t

class class_test():
   def test_def(q):
       test_msg = test('Hi')
       print (test_msg)
1
  • 1
    What happens when you run code above? Commented Mar 7, 2015 at 8:00

1 Answer 1

16

To call the class method, you can create an instance of the class and then call an attribute of that instance (the test_def method).

def test(t):
    return t

class ClassTest(object):
    def test_def(self):
        msg = test('Hi')
        print(msg)

# Creates new instance.
my_new_instance = ClassTest()
# Calls its attribute.
my_new_instance.test_def()

Alternatively you can call it this way:

ClassTest().test_def()

Sidenote: I made a few changes to your code. self should be used as first argument of class methods when you define them. object should be used in a similar manner.

Sign up to request clarification or add additional context in comments.

4 Comments

Want access the test(t) function inside of the ClassTest,
@GThamizh What do you mean? Aren't you already using test(t) in test_def()?
@sqrcompass what code exactly are you using, what do you expect to get and what do you get?
@sqrcompass are you by any chance trying to access test in another module where you have imported ClassTest (in the example above)? That is, trying something like ClassTest.test.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.