Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I call outside function from class in python

Tags:

python-3.x

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)
like image 547
GThamizh Avatar asked Mar 07 '15 07:03

GThamizh


1 Answers

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):
        test_msg = test('Hi')
        print(test_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.

like image 66
user Avatar answered Sep 22 '22 06:09

user