如何在另一个函数中使用一个函数中的局部定义变量?

How do I use a locally defined variable from one function in another function?

我还是 python (PYTHON 3.9.1) 的新手,我正在尝试编写一个程序来获取 IP 地址,然后对其进行哈希处理。我定义了一个获取 ip 地址的函数,然后删除点并将其转换为十六进制(我只希望它散列 ip 地址的十六进制)。然后我定义了一个使用 SHA256 散列的函数。但是现在当我想在第一个函数中使用本地定义的变量来定义 Hexed IP 地址时,在第二个函数中对其进行哈希处理,我只是不知道该怎么做。由于 Hexed IP 地址不是全局定义的,我不能在其他函数中使用它。我可以将散列函数的代码放入第一个函数中,我做到了并且它有效,但我不喜欢它,它让我的代码变得混乱,我认为必须有另一种方法来做到这一点.

主要问题是:如何在另一个函数中使用一个函数中的局部定义变量?

这是我的代码:

import hashlib as hb
import socket

def get_ip():
    hostname = socket.gethostname()
    ip = socket.gethostbyname(hostname) #If I was to print it, it would give a propper IP address
    dotless_ip = ip.replace(".","") 
    hexidecimal_ip = hex(int(dotless_ip))

def sha256(): #This is the hashing function that uses SHA256 algorythm for hashing.
    SHA256_convert = bytearray(input("Enter text to convert to SHA256 hash: "), "utf8") #If I was to hash something with this function, I would need to input stuff myself.
    hasher = hb.sha256()
    hasher.update(SHA256_convert)
    print(hasher.hexdigest()) #This function works too, and the problem is not in it.

正如您所见,get_ip() 函数中有一个本地定义的变量 hexidecimal_ip。 我想在我的 sha256() 函数中使用这个本地定义的变量,所以我所做的是:

def sha256():
    SHA256_convert = bytearray(hexidecimal_ip), "utf8") #changing user input to a variable.
    hasher = hb.sha256()
    hasher.update(SHA256_convert)
    print(hasher.hexdigest()) 

但是当然它不起作用,因为变量不是全局定义的,所以我接下来做的是:

def get_ip():
    hostname = socket.gethostname()
    ip = socket.gethostbyname(hostname)
    dotless_ip = ip.replace(".","") 
    hexidecimal_ip = hex(int(dotless_ip))
    return hexidecimal_ip #added a return statement here, in hopes that it will make the variable accessible globaly ( I still don't understand how return works )

def sha256():
    SHA256_convert = bytearray(hexidecimal_ip), "utf8") #changing user input to a variable.
    hasher = hb.sha256()
    hasher.update(SHA256_convert)
    print(hasher.hexdigest()) 

然而这也不起作用,所以对我来说唯一剩下的方法就是将它全部放入一个函数中,我做了并且它起作用了:

def get_ip():
    hostname = socket.gethostname()
    ip = socket.gethostbyname(hostname)
    print("Your IP address is:",ip) #I added a few print statements to check if function works and it does
    dotless_ip = ip.replace(".","")
    hexidecimal_ip = hex(int(dotless_ip))
    print("Your IP address in hexidecimals is: ", hexidecimal_ip) 
    ip_hasher = hb.sha256() #changed the variable name a little bit, but it doesn't really matter
    ip_hasher.update(bytearray(hexidecimal_ip, "utf8"))
    print("Your hashed IP address is: ",ip_hasher.hexdigest())

所以在对我的问题进行了这么长时间的介绍之后,我的问题仍然存在:如何在另一个函数中使用一个函数中的本地定义变量?

有很多方法可以做到这一点:-

可以将hexidecimal_ip作为参数传给sha256函数返回后,例如:-

def get_ip():
    .
    .
    return hexidecimal_ip

def sha256(hexidecimal_ip):
    SHA256_convert = bytearray(hexidecimal_ip), "utf8")
    .
    .

在主函数中你可以做:-

def main():
    hexidecimal_ip = get_ip()
    sha256(hexidecimal_ip)

当然还有其他方法,但这可能是最好的