【问题标题】:NamError: Name 'self' is not definedNameEerror:未定义名称“self”
【发布时间】:2019-03-06 17:38:31
【问题描述】:

如果我尝试运行此脚本,我收到错误“NamError: Name 'self' is not defined”,请帮我解决这个问题,我是 Python 新手。我试图通过阅读不同的资料来解决这个问题,但没有奏效。

#!/usr/bin/env python3
import hmac
import hashlib
import base64
import argparse

# Values that are required to calculate the signature. These values should
# never change.
DATE = "11111111"
SERVICE = "ses"
MESSAGE = "SendRawEmail"
TERMINAL = "aws4_request"
VERSION = 0x04

def sign(key, msg):
    return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest()

def calculateKey(secretAccessKey, region):
    signature = sign(("AWS4" + secretAccessKey).encode('utf-8'), DATE)
    signature = sign(signature, region)
    signature = sign(signature, SERVICE)
    signature = sign(signature, TERMINAL)
    signature = sign(signature, MESSAGE)
    signatureAndVersion = bytes([VERSION]) + signature
    smtpPassword = base64.b64encode(signatureAndVersion)
    print(smtpPassword.decode('utf-8'))

def main(self):
    parser = argparse.ArgumentParser(description='Convert a Secret Access Key for an IAM user to an SMTP password.')
    parser.add_argument('--secret')
    help='my_access_id_here',
    required=True,
    action="store"
    parser.add_argument('--region')
    help='us-west-2',
    required=True,
    choices=['us-east-1','us-west-2','eu-west-1'],
    action="store"
    args = parser.parse_args()

    calculateKey(args.secret,args.region)

main(self)

【问题讨论】:

  • def main(self) 替换为def main() 并调用它为main()
  • 我将问题回滚到其原始状态,因为所做的编辑通过删除导致问题的部分更改了代码,这使得问题完全没有意义。编辑请注意:切勿更改问题中的代码。如果有什么问题——这就是问题首先存在的原因——必须在答案中加以处理。
  • 它不起作用,我试图删除它并开始但又出现了另一个错误。任何人都可以尝试运行它,看看他们是否能够正确运行它。谢谢

标签: python amazon-ec2


【解决方案1】:

您需要从 main() 中删除 self,因为 self 仅在它是类方法时才需要,常规函数没有 self 作为第一个参数。

引用自文档:

通常,方法的第一个参数称为 self。这只不过是一个约定:名称 self 对 Python 绝对没有特殊含义。

请参阅下面的文档了解更多信息

documentation

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-23
    • 2017-11-20
    相关资源
    最近更新 更多