簡體   English   中英

在Python中從內部類函數調用全局函數

[英]Calling a global function from an inner class function in Python

這是我的代碼要點

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

我經歷了很多問題,但是他們正在從另一個類調用一個類函數。 我只想從內部類調用全局函數。

問題是我無法從內部函數訪問全局函數。

我該如何實施呢?

是的,你可以這么做....

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)

輸出:

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

只要您發送帶有類內函數的self ,就應該沒問題。 例如,這可以工作:

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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM