python把函数中的变量传出去_python 3.2如何在函数之间传递变量中的数据

How would I store and pass the contents of r from main into two? It will print r if I make it r = something fixed, but how do I pass and hold variable contents into r. I tried random.getstate/setstate but it was saying "function object not subscriptable".

import random

from random import randrange

def main():

r = random.randrange(1,13,1)

print (r)

r = random.randrange(1,13,1)

def two():

if r==7 or r==11:

print (r)

else:

print (r)

main()

two()

解决方案

Well, depending on the situation, you either want to make a class or return the data, then pass it in as an argument, the latter is probably what you want given your code, so, for example:

def main():

...

r = do_something()

...

return r

def two(r):

...

do_something_else(r)

...

r = main()

two(r)

If this was happening within something you could define as an entity, you could do it in a class:

class Main():

def main(self):

...

self.r = do_something()

...

def two(self):

...

do_something_else(self.r)

...

main = Main()

main.main()

main.two()

However, in this case, this is unnecessary as you are creating a class that doesn't really encapsulate anything.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值