首页 > 解决方案 > 类中的另一个函数在一个函数中使用局部变量

问题描述

由于某些情况,我只能将参数传递给类中的一个函数。

例子:

class win1():
    def __init__(self):
        self.diction = dict()
        self.x = self.wanted_touse()
        #is it possible to make it here? If yes, it will be good to be like this
        # self.X = X or self.y = Y (is this even possible without passing an argument in it?)

    def fun(self, X,Y):
        self.x = X
        self.y = Y

    def wanted_touse(self):
        #I wanted to use X and Y here while at the same time I cannot pass the argument to this function because of some circumstances.
        #Here with some functions to make the dictionary for self.x example for x in enumerate(self.x)

        self.diction[something] = something

我想了解是否可以在函数中使用win1变量want_touse

标签: pythonclassvariables

解决方案


在 中定义您的属性__init__(),然后在您的fun()函数中修改它,如下所示:

class win1():
    def __init__(self):
       self.x = None

    def fun(self, X,Y):
        self.x = X

    def wanted_touse(self):
        pass
        #do whatever you want with self.x here, so long as you've run your fun() function and changed self.x as you intended.

此示例仅使用单个变量。您可以根据需要将其应用于其他变量。


推荐阅读