[英]python - NameError on a variable declared outside class
Python newbie and learning how to use a class . Python 新手并学习如何使用class 。 I've defined a class which has a method - "create" that uses a parameter (private_key) as part of a command to create a token.
我定义了一个 class ,它有一个方法 - “create”,它使用参数(private_key)作为命令的一部分来创建令牌。
Here's the command:这是命令:
jwt.encode(payload, private_key, algorithm="RS256", headers=additional_headers).decode("utf-8")
I use a function outside of the class to populate the variable private_key.我在 class 之外使用 function 来填充变量 private_key。
Here's the code (myToken.py):这是代码(myToken.py):
class MyTokenMgr():
def __init__(self):
pass
def create(self, privkey, email):
<MORE CODE HERE TO CREATE TOKEN>
# Function to load key from file
def load_privkey(privkey_filename):
with open(privkey_filename, 'r') as f:
data = f.read()
return data
#Read the private local key
private_key = load_privkey('testkeys/jwt-key')
print('This is the local private key:', private_key)
Here's my problem.这是我的问题。 When I run python locally from command line.
当我从命令行本地运行 python 时。 I want to test instantiation of the object.
我想测试 object 的实例化。 However, I get NameError and variable is not defined:
但是,我得到 NameError 并且未定义变量:
$ python
Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 23:09:28) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from lib.myToken import MyTokenMgr
This is the local private key: -----BEGIN RSA PRIVATE KEY-----
MIIJKAIBAAKCAgEAtr454soMHt7IYU+9mM6OmtzOK/i2ajNwtybYY/fQf3vMOUt8
'''
'''
-----END RSA PRIVATE KEY-----
>>> newtoken = MyTokenMgr()
>>> newtoken.create(private_key,'test@gmail.com')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'private_key' is not defined
You can see that I printed out the variable so I can view the key and confirm its used by the variable.您可以看到我打印了变量,因此我可以查看密钥并确认变量使用了它。 So why am I still getting the is not defined error?
那么为什么我仍然收到未定义错误? What concept am i misunderstanding?
我误解了什么概念? Thanks for your help.
谢谢你的帮助。
from lib.myToken import MyTokenMgr
You're only importing the symbol MyTokenMgr
.您只导入符号
MyTokenMgr
。 If you want to import other symbols, you need to specify them as well when importing:如果要导入其他符号,还需要在导入时指定它们:
from lib.myToken import MyTokenMgr, private_key
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.