python 子函数调用父函数的变量_python – 从另一个函数调用一个函数内部定义的变量...

如果我有这个:

def oneFunction(lists):

category=random.choice(list(lists.keys()))

word=random.choice(lists[category])

def anotherFunction():

for letter in word: #problem is here

print("_",end=" ")

我之前已经定义了列表,因此oneFunction(列表)可以很好地工作.

我的问题是在第6行调用单词.我试图用相同的单词= random.choice(lists [category])定义在第一个函数之外定义单词,但这使得单词总是相同的,即使我调用oneFunction(列表) ).

我希望每次调用第一个函数然后第二个函数都有不同的单词.

如果不在oneFunction(列表)之外定义该单词,我可以这样做吗?

解决方法:

是的,您应该考虑在Class中定义函数,并将word作为成员.这比较干净

class Spam:

def oneFunction(self,lists):

category=random.choice(list(lists.keys()))

self.word=random.choice(lists[category])

def anotherFunction(self):

for letter in self.word:

print("_",end=" ")

创建类后,必须将其实例化为Object并访问成员函数.

s = Spam()

s.oneFunction(lists)

s.anotherFunction()

另一种方法是使oneFunction返回单词,以便您可以在anotherFunction中使用oneFunction而不是word

>>> def oneFunction(lists):

category=random.choice(list(lists.keys()))

return random.choice(lists[category])

>>> def anotherFunction():

for letter in oneFunction(lists):

print("_",end=" ")

最后,您还可以创建anotherFunction,接受word作为参数,您可以从调用oneFunction的结果中传递该参数

>>> def anotherFunction(words):

for letter in words:

print("_",end=" ")

>>> anotherFunction(oneFunction(lists))

标签:python,variables,function

来源: https://codeday.me/bug/20190916/1806698.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值