【问题标题】:Using local variable within a function by another function in a class类中的另一个函数在一个函数中使用局部变量
【发布时间】:2019-03-30 01:06:57
【问题描述】:

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

例子:

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函数。

【问题讨论】:

  • 你试过上面的方法了吗?如果您在 init 方法中创建 X 和 Y,您应该能够通过其他函数中的 self 参数访问它们
  • 是的,实际上我想在 init 中创建它,但问题是它不会将它传递给 init,它需要我在 init 中包含参数才能使用 X 或 Y。
  • self 上设置的属性仍然可以被同一实例上的其他方法访问,是的。这就是上课的重点;它们捆绑了 state(存储在属性中)和 functionality(绑定到实例的方法)。
  • @Beginner:win1.fun()中可以随意设置self.Xself.Y,不要求属性只能在__init__中设置。
  • 这个问题有示例代码,以及对 OP 试图做什么的简单/清晰的解释。我不明白为什么这里有几个反对票。我认为我们能够帮助@Beginner 解决这个问题。

标签: python class variables


【解决方案1】:

__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.

这个例子只使用了一个变量。您可以根据需要将其应用于其他变量。

【讨论】:

  • 没有变量的“定义”。 __init__ 部分是可选的。
  • @martjin 我对最佳实践的理解是实例变量应该始终在 init 中初始化,即使它只是为 None。这大大提高了可读性。
  • @MartijnPieters 我没有意识到这一点。那么,在这个例子中,第一次在 fun() 函数中引用 self.x 是完全没问题的?
  • @pypypy:虽然它可以提供帮助,但它不是必需的,并不总是必要的。仅限于一小部分功能的属性可能会导致__init__ 中的混乱程度超出其价值。
  • @pypypy:我不是在讨论这是否是一个更好的风格想法。我所做的只是指出没有技术需要这样做。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-03
  • 1970-01-01
  • 2016-08-05
  • 1970-01-01
  • 2014-07-31
  • 1970-01-01
  • 2023-02-26
相关资源
最近更新 更多