【发布时间】:2019-06-11 03:09:06
【问题描述】:
我创建了一个类,我想在其中将 self.variable 传递给方法中的可选参数。原因是因为我想将信息存储在以其他方法制作的 Self.variable 中,但是,如果我使用该方法,我想选择用我自己的手动信息覆盖 self.variable。
遗憾的是,这是不允许的,所以我想知道为什么不这样做!? 另外,我想知道是否有人知道实现相同目标的 Pythonic 方法?
这是我尝试过的一个例子:
# example:
class Example(Object)
def __init__(self):
self.variable = []
def fill_variable(self):
self.variable = [random.randint(1,10)] * 10
def use_variable(self, random_numbers = self.variable)
print(random)
test.Example()
test.fill_variable()
test.use_variable()
# or
test.use_variable(random_numbers=[1,2,3,4,5,6,7,8,9,10])
我的期望是 test.use_variable() 会打印 10 随机数
那test.use_variable(random_numbers=[1,2,3,4,5,6,7,8,9,10])会
print(1,2,3,4,5,6,7,8,9,10)
感谢您的帮助和解释!
【问题讨论】: