Chandrapal
Chandrapal

Reputation: 31

Calling a global function from an inner class function in Python

Here's a gist of my code

def global_func(text):
  ..do something with text..

class Data():
  def inner_func(some_text):
    # do something
    analysed_data = global_func("something")
    # do something else

I have gone through lots of questions, but they were on calling a class function from another class. I just want to call a global function from inner class.

The problem is I cannot access the global function from inner function.

How can I implement it ?

Upvotes: 1

Views: 8952

Answers (2)

Fawaz
Fawaz

Reputation: 21

Yes you can do that....

def addOne(x):
    return x+1
class Number():
    def __init__(self, value):
        self.value = value
    def printAddedValue(self,x):
        print("Value inside is: ", self.value)
        print("Here we called the global function")
        print(addOne(x))

num = Number(3)
num.printAddedValue(6)

Output:

Value inside is:  3
Here we called the global function
7

Upvotes: 1

internetional
internetional

Reputation: 322

Should be no problem as long as you send self with in-class function. This, for example, works:

def global_func(text):
  print("Global function prints %s" % text)

class Data():
  def inner_func(self):
    # do something
    analysed_data = global_func("something")
    # do something else

Data().inner_func()

Upvotes: 1

Related Questions