小编hch*_*chw的帖子

带有 ABC mixin 的 NamedTuple 类

我的问题如下:我想创建一个继承自typing.NamedTuple的类和另一个抽象类中的mixin。理想情况下我想做这样的事情:

from typing import *
from abc import ABC, abstractmethod

class M(ABC):
    @abstractmethod
    def m(self, it: Iterable[str]) -> str:
        pass

class N(NamedTuple, M):
    attr1: str

    def m(self, it):
        return self.attr1 + it
Run Code Online (Sandbox Code Playgroud)

当我现在尝试这样做时,我收到此错误:

TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases
Run Code Online (Sandbox Code Playgroud)

我知道我可以这样做:

from typing import *
from abc import ABC, abstractmethod

class M(ABC):
    @abstractmethod
    def m(self, it: Iterable[str]) -> str:
        pass

class NT(NamedTuple):
    attr1: str

class N(NT, …
Run Code Online (Sandbox Code Playgroud)

python abc namedtuple python-3.6

6
推荐指数
1
解决办法
1172
查看次数

Cant Pickle记住了类实例

这是我正在使用的代码

import funcy

@funcy.memoize
class mystery(object):

    def __init__(self, num):
        self.num = num

feat = mystery(1)

with open('num.pickle', 'wb') as f:
    pickle.dump(feat,f)
Run Code Online (Sandbox Code Playgroud)

这给了我以下错误:

PicklingError: Can't pickle <class '__main__.mystery'>: it's not the 
same object as __main__.mystery
Run Code Online (Sandbox Code Playgroud)

我希望1)理解为什么会这样,2)找到一个允许我挑选对象的解决方案(不删除memoization).理想情况下,解决方案不会改变对pickle的调用.

用funcy运行python 3.6 == 1.10

提前致谢!

python memoization python-3.x funcy

5
推荐指数
1
解决办法
244
查看次数

标签 统计

python ×2

abc ×1

funcy ×1

memoization ×1

namedtuple ×1

python-3.6 ×1

python-3.x ×1