从python中的函数外部访问函数变量

时间:2019-11-25 19:36:22

标签: python function

我有一个python函数,想从函数外部检索一个值。不使用全局变量怎么能做到这一点。我有个主意,如果python中的函数是对象,那么这可能是正确的解决方案?

def check_difficulty():
    if (difficulty == 1):
        check_difficulty.tries = 10
    elif (difficulty == 2):
        check_difficulty.tries = 5
    elif (difficulty == 3):
        check_difficulty.tries = 3


try:
    difficulty = int(input("Choose your difficulty: "))
    check_difficulty()

except ValueError:
    difficulty = int(input("Type a valid number: "))
    check_difficulty()

while check_difficulty.tries > 0:

我是python的新手,所以请问...

4 个答案:

答案 0 :(得分:1)

def check_difficulty(difficulty):
    if (difficulty == 1):
        return 10
    elif (difficulty == 2):
        return 5
    elif (difficulty == 3):
        return 3

tries = 0
while tries > 0:
    difficulty = int(input("Choose your difficulty: "))

    tries = check_difficulty(difficulty)
    tries = tries - 1

答案 1 :(得分:0)

如果使用while循环并以结构化的方式将所有内容放入其中,则将不需要功能。

答案 2 :(得分:0)

您可以将其更改为一个类以进行尝试:

class MyClass:
  def __init__(self):
    self.tries = 0
  def check_difficulty(self, difficulty):
    if (difficulty == 1):
        self.tries = 10
    elif (difficulty == 2):
        self.tries = 5
    elif (difficulty == 3):
        self.tries = 3

ch = MyClass()

try:
    difficulty = int(input("Choose your difficulty: "))
    ch.check_difficulty(difficulty)

except ValueError:
    difficulty = int(input("Type a valid number: "))
    ch.check_difficulty(difficulty)


ch.tries
# 5

答案 3 :(得分:0)

如果您想在当前代码的构造内回答问题,只需尝试一下即可,函数之前除外。创建函数后,您可以在代码中不需要的任何位置调用函数。像这样:

for(i in 2:10){

   variable_1 <- paste0("a_", i)
   variable_2 <- paste0("b_", i)
   variable_3 <- paste0("c_", i)
   data1 <- data1 %>%
    mutate(!! variable_3 := case_when(is.na(!! rlang::sym(variable_1)) & 
     !is.na(!! rlang::sym(variable_2) )~ 0,
                             TRUE ~ 1))
  }

但是,我将不得不同意其他答案,只是将所有内容放到同一循环中,而您不必为此担心。我最近创建了一个猜谜游戏,实际上它与此类似。这是该代码的难度部分:

try:
    difficulty = int(input("Choose your difficulty: "))
    check_difficulty()

except ValueError:
    difficulty = int(input("Type a valid number: "))
    check_difficulty()

def check_difficulty():
    if (difficulty == 1):
        check_difficulty.tries = 10
    elif (difficulty == 2):
        check_difficulty.tries = 5
    elif (difficulty == 3):
        check_difficulty.tries = 3


while check_difficulty.tries > 0: