简体   繁体   English

为什么我在 globals() 中找不到我的变量?

[英]Why can't I find my variable in globals()?

I created a function to create a variable for random DNA.我创建了一个 function 来为随机 DNA 创建一个变量。 But when I want to look if rdna is in globals() I get False as result但是当我想查看rdna是否在globals()中时,结果为False

from random import choice
def randomseq():
  global rdna
  rdna=""
  largo = int(input("Sequence Length: "))
  for count in range(largo):
    rdna+=choice("CGTA")
  return rdna
rdna in globals()
False

Why can't I get True ?为什么我不能得到True

rdna in globals() will search for the value stored in the variable rdna in globals() . rdna in globals()将搜索存储在globals()中的变量rdna中的值。 If you literally want to search for "rdna" you should make it a string literal:如果您确实想搜索"rdna" ,则应将其设为字符串文字:

"rdna" in globals()

Take this example:举个例子:

x = 1
my_var = 'x'
print(my_var in globals())

This prints True , but not because my_var is a global variable, but because x is.这会打印True ,但不是因为my_var是全局变量,而是因为x是。 globals() returns a dictionary with all global variables and their values, my_var in globals() in this case is the same as asking 'x' in globals() . globals()返回一个包含所有全局变量及其值的字典,在这种情况下 globals() 中的my_var in globals()中询问'x' in globals()相同。

You want this:你要这个:

'rdna' in globals()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM