【发布时间】: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.X和self.Y,不要求属性只能在__init__中设置。 -
这个问题有示例代码,以及对 OP 试图做什么的简单/清晰的解释。我不明白为什么这里有几个反对票。我认为我们能够帮助@Beginner 解决这个问题。