簡體   English   中英

Python:從調用函數中獲取價值

[英]Python: Getting value from calling function

在Python中,是否有一種簡單的方法可以使被調用函數從調用函數/類中獲取值? 我不確定我是否應該正確地表述,但是我正在嘗試執行以下操作:

class MainSection(object):
    def function(self):
        self.var = 47  # arbitrary variable 
        self.secondaryObject = secondClass()  # Create object of second class
        self.secondaryObject.secondFunction(3)  # call function in that object

class secondClass(object):
    def secondFunction(self, input)
        output = input + self.var  # calculate value based on function parameter AND variable from calling function
        return output
        #Access self.var from MainSection

這可能是我對Python缺乏了解,但是我很難在這里找到明確的答案。 做到這一點的最佳方法就是將我想要的變量作為另一個第二個參數傳遞給第二個類嗎? 如果不同,這些文件位於單獨的文件中。

做到這一點的最佳方法就是將我想要的變量作為另一個第二個參數傳遞給第二個類嗎?

是的,尤其是在對象之間只有短暫關系的情況下:

class secondClass(object):
    def secondFunction(self, input, var_from_caller)
        output = input + var_from_caller  # calculate value based on function parameter AND variable from calling function
        return output

如果願意,您甚至可以遍歷整個對象:

class secondClass(object):
    def secondFunction(self, input, calling_object)
        output = input + calling_object.var  # calculate value based on function parameter AND variable from calling function
        return output

如果關系是永久的,則可以考慮將對相關對象的引用存儲在實例變量中:

class MainSection(object):
    def function(self):
        self.var = 47  # arbitrary variable 
        self.secondaryObject = secondClass(self)  # Create object of second class
        self.secondaryObject.secondFunction(3)  # call function in that object

...
class secondClass(object):
    def __init__(self, my_friend):
        self.related_object = my_friend

    def secondFunction(self, input)
        output = input + self.related_object.var  # calculate value based on function parameter AND variable from calling function
        return output
        #Access self.var from MainSection

暫無
暫無

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

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