简体   繁体   中英

Understanding the usage of class methods

im ac 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()

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM