Вопрос:

Understanding the usage of class methods

python

41 просмотра

1 ответ

3 Репутация автора

im a c programmer and im fairly new to python, i have trouble understanding why class methods are being used in this piece of code

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)

Mnemonic is not being used as a parent class anywhere, i can see why its being used in detect_language() but i dont understand why its being used on _get_directory()

Автор: Mikey Salas Источник Размещён: 08.11.2017 10:35

Ответы (1)


0 плюса

306 Репутация автора

Решение

Your concern is valid, this is not best-practice for writing python class methods. There is no need here for the @classmethod parameter, and for example, the _get_directory() method might as well be its own function as it has no connection to the class. In java, everything has to be a class or in a class, so this looks like python code from a java dev.

Автор: Asher Mancinelli Размещён: 08.11.2017 10:58
Вопросы из категории :
32x32