gpt4 book ai didi

python - 执行此操作的 "metaclass"方法是什么?

转载 作者:太空宇宙 更新时间:2023-11-03 11:05:04 30 4
gpt4 key购买 nike

我想编写一个程序,它接受一个数字 p 作为输入,并为一个遵循整数算术模 p 的数字生成一个类型构造函数作为输出。

目前为止

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

这很好用,但我想知道执行此操作的 Pythonic 方法是什么,据我所知会使用元类。

最佳答案

像这样:

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)

关于python - 执行此操作的 "metaclass"方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22236440/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com