我是一名程序员,对于python来说还是一个新手,我无法理解为什么在这段代码中使用类方法
class Mnemonic(object):
def __init__(self, language):
self.radix = 2048
@classmethod
def _get_directory(cls):
return os.path.join(os.path.dirname(__file__), 'wordlist')
@classmethod
def list_languages(cls):
return [f.split('.')[0] for f in os.listdir(cls._get_directory()) if f.endswith('.txt')]
@classmethod
def normalize_string(cls, txt):
if isinstance(txt, str if sys.version < '3' else bytes):
utxt = txt.decode('utf8')
elif isinstance(txt, unicode if sys.version < '3' else str):
utxt = txt
else:
raise TypeError("String value expected")
return unicodedata.normalize('NFKD', utxt)
@classmethod
def detect_language(cls, code):
code = cls.normalize_string(code)
first = code.split(' ')[0]
languages = cls.list_languages()
for lang in languages:
mnemo = cls(lang)
if first in mnemo.wordlist:
return lang
raise ConfigurationError("Language not detected")
def generate(self, strength=128):
# Do Stuff
def to_entropy(self, words):
# Do Stuff
def to_mnemonic(self, data):
# Do Stuff
def check(self, mnemonic):
# Do Stuff
def expand_word(self, prefix):
# Do Stuff
def expand(self, mnemonic):
# Do Stuff
@classmethod
def to_seed(cls, mnemonic, passphrase=''):
mnemonic = cls.normalize_string(mnemonic)
passphrase = cls.normalize_string(passphrase)
return PBKDF2(mnemonic, u'mnemonic' + passphrase, iterations=PBKDF2_ROUNDS, macmodule=hmac, digestmodule=hashlib.sha512).read(64)
助记符在任何地方都没有被用作父类,我可以看到它在detect_language()
中被使用的原因,但我不明白为什么它被用在_get_directory()
上
答案 0 :(得分:0)
您的关注是有效的,这不是编写python类方法的最佳实践。这里不需要@classmethod
参数,例如,_get_directory()
方法也可能是它自己的函数,因为它没有与类的连接。在java中,一切都必须是类或类,所以这看起来像是java dev中的python代码。