Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
150 views
in Technique[技术] by (71.8m points)

python 3.2 how to pass data in variables between functions

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()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...