-1
我試圖用我在Java中學到的相同方式編寫OO Python代碼,這可能是我要去南方的地方。我有一個主要腳本和一個其他人寫的我修改過的類。我在主腳本中調用這個類,但是我使用的每一種技術我都得不到[class name]。爲什麼我的Python類不可調用?
下面是最近的嘗試。這是主要劇本。爲了安全起見,已刪除變量directory.pairs。
import yaml
import pysftp
import FingerprintKey
with open('config/config.yaml') as settings:
cfg = yaml.load(settings)
host = cfg['host']
username = cfg['username']
password = cfg['password']
serverkey = cfg['fingerPrint']
x = FingerprintKey(serverkey)
options = pysftp.CnOpts()
options.hostkeys.clear()
options.hostkeys.add('www.example.com', u'ecdsa-sha2-nistp384', x)
with pysftp.Connection(host, username=username, password=password, cnopts=options) as sftp:
#for source, destination in directoryPairs.items():
#sftp.get_d(source, destination, preserve_mtime=True)
#if sftp.exists(source):
#files = sftp.listdir(source)
#for f in files:
#sftp.remove(os.path.join(source, f))
sftp.close()
下面是類FingerprintKey.py
import hashlib as hl
def trim_fingerprint(fingerprint):
if fingerprint.startswith('ecdsa-sha2-nistp384 384 '):
return fingerprint[len('ecdsa-sha2-nistp384 384 '):]
return fingerprint
def clean_fingerprint(fingerprint):
return trim_fingerprint(fingerprint).replace(':', '')
class FingerprintKey:
def __init__(self, fingerprint):
self.fingerprint = clean_fingerprint(fingerprint)
def compare(self, other):
if callable(getattr(other, "get_fingerprint", None)):
return other.get_fingerprint() == self.fingerprint
elif clean_fingerprint(other) == self.get_fingerprint():
return True
elif hl.md5(other).digest().encode('hex') == self.fingerprint:
return True
else:
return False
def __cmp__(self, other):
return self.compare(other)
def __contains__(self, other):
return self.compare(other)
def __eq__(self, other):
return self.compare(other)
def __ne__(self, other):
return not self.compare(other)
def get_fingerprint(self):
return self.fingerprint
def get_name(self):
return u'ecdsa-sha2-nistp384'
def asbytes(self):
# Note: This returns itself.
# That way when comparisons are done to asbytes return value,
# this class can handle the comparison.
return self
這些文件的兩者都是在同一個目錄。
在主腳本,'FingerprintKey'指與該名稱的模塊。該模塊中的類(具有相同的名稱)稱爲'FingerprintKey.FingerprintKey'。 – mkrieger1
哦!好。所以它不像Java那樣必須將該文件命名爲與該類相同的文件。 –