What is the metaclass method?

I want to write a program that takes a number p as input and outputs a constructor type for a number that obeys integer arithmetic modulo p.

I still have

def IntegersModP(p):
   N = type('IntegersMod%d' % p, (), {})

   def __init__(self, x): self.val = x % p
   def __add__(a, b): return N(a.val + b.val)
   ... (more functions) ...    

   attrs = {'__init__': __init__, '__add__': __add__, ... }

   for name, f in attrs.items():
      setattr(N, name, f)

   return N

This works fine, but I would like to know what Pythonic is for this, I understand it will use metaclasses.

+4
source share
2 answers

, , , class. , . , ModularInteger , , , :

def integers_mod_p(p):
    class IntegerModP(object):
        def __init__(self, n):
            self.n = n % IntegerModP.p
        def typecheck(self, other):
            try:
                if self.p != other.p:
                    raise TypeError
            except AttributeError:
                raise TypeError
        def __add__(self, other):
            self.typecheck(other)
            return IntegerModP(self.n + other.n)
        def __sub__(self, other):
            ...
    IntegerModP.p = p
    IntegerModP.__name__ = 'IntegerMod{}'.format(p)
    return IntegerModP
+1

:

def IntegerModP(p):  # class factory function
    class IntegerModP(object):
        def __init__(self, x):
            self.val = x % p
        def __add__(a, b):
            return IntegerModP(a.val + b.val)
        def __str__(self):
            return str(self.val)
        def __repr__(self):
            return '{}({})'.format(self.__class__.__name__, self.val)

    IntegerModP.__name__ = 'IntegerMod%s' % p  # rename created class
    return IntegerModP

IntegerMod4 = IntegerModP(4)
i = IntegerMod4(3)
j = IntegerMod4(2)
print i + j        # 1
print repr(i + j)  # IntegerMod4(1)
+2

Source: https://habr.com/ru/post/1530506/


All Articles