我正在尝试使用类,但对它们仍然陌生。我对如何从父类继承属性以及初始化子类的新属性感到困惑。我发现父属性是可调用的,但不是我定义的子属性。请参阅下面的代码:
import random
import hashlib
import base64
import requests
import json
import urllib3
import getpass
# Disable warning re: server certificate checking turned off
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
class vsa:
def __init__(self):
self.vsa_token = self.api_authentication()
self.headers = {'Authorization': "Bearer " + self.vsa_token}
self.url = "example.com"
def api_authentication(self):
while True:
username = input("Enter your username: ")
password = getpass.getpass("Enter your password: ")
vsa = "example.com/api/auth"
random_integer = random.randint(5000, 50000)
CoveredSHA256HashTemp_object = hashlib.sha256()
CoveredSHA256HashTemp_object.update(('%s%s' % (password, username)).encode('utf-8'))
CoveredSHA256HashTemp = CoveredSHA256HashTemp_object.hexdigest()
CoveredSHA256Hash_object = hashlib.sha256()
CoveredSHA256Hash_object.update(('%s%d' % (CoveredSHA256HashTemp, random_integer)).encode('utf-8'))
CoveredSHA256Hash = CoveredSHA256Hash_object.hexdigest()
CoveredSHA1HashTemp_object = hashlib.sha1()
CoveredSHA1HashTemp_object.update(('%s%s' % (password, username)).encode('utf-8'))
CoveredSHA1HashTemp = CoveredSHA1HashTemp_object.hexdigest()
CoveredSHA1Hash_object = hashlib.sha1()
CoveredSHA1Hash_object.update(('%s%d' % (CoveredSHA1HashTemp, random_integer)).encode('utf-8'))
CoveredSHA1Hash = CoveredSHA1Hash_object.hexdigest()
auth = "user=%s, pass2=%s, pass1=%s, rpass2=%s, rpass1=%s, rand2=%d, twofapass=:undefined" % (username, CoveredSHA256Hash, CoveredSHA1Hash, CoveredSHA1Hash, CoveredSHA256Hash, random_integer)
encode = base64.urlsafe_b64encode(('%s' % auth).encode('UTF-8')).decode('ascii')
headers = { 'Authorization' : 'Basic %s' % encode }
r = requests.get(vsa, headers=headers, verify=False)
data = r.text
parsed_data = json.loads(data)
if parsed_data['ResponseCode'] == 0:
print("nVSA token successfully retrievedn")
vsa_token = parsed_data['Result']['Token']
return vsa_token
else:
print("Unauthorized")
def get_vsa_token(self):
return self.vsa_token
class agents(vsa):
def __init___(self):
vsa.__init__(self)
self.call = "/asetmgmt/agents"
def get_agents(self):
list_agents = []
r = requests.get(self.url + self.call, headers=self.headers, verify=False)
data = r.text
parsed_data = json.loads(data)
all_agents = parsed_data
for agents in all_agents['Result']:
list_agents.append((agents['AgentName']))
return list_agents
session = agents()
print(session.call)
最后一个命令 -print(session.call)
给了我以下输出:
AttributeError: 'agents' object has no attribute 'call'
但是,我已经获取了(我认为是(此代码的相关部分并通过 PythonTutor 运行它,并看到调用属性正在初始化?
PythonTutor 链接到代码
我对自己做错了什么感到茫然。我发现我可以在agents.__init__(self)
块之外初始化变量,这工作正常:
class agents(vsa):
call = "/assetmgmt/agents"
def __init___(self):
vsa.__init__(self)
但现在困扰我的是概念性的东西。我构建它的方式是愚蠢的吗?您将如何更好地构建?
感谢您提供的任何见解。
感谢为我提供解决方案的@Blckknght,即修复我犯的错别字......
__init___
!=__init__
总是简单的事情被忽视。我很高兴我在这里发布了一个问题,而不是不断调试和尝试其他解决方案(我做了大约 30 分钟(。
谢谢!