相关疑难解决方法(0)

从python中的基类继承namedtuple

是否可以生成namedtuple从基类继承的 a?

我想要的是Circleand Rectangleare namedtuples 并且是从一个公共基类 ('Shape') 继承的:

from collections import namedtuple

class Shape:
    def addToScene(self, scene):
         ...

Circle=namedtuple('Circle', 'x y radius')
Rectangle=namedtuple('Rectangle', 'x1 y1 x2 y2')
Run Code Online (Sandbox Code Playgroud)

我该怎么做?

python inheritance namedtuple

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

为什么通过装饰器与类主体在class .__ slots__分配中存在差异?

我正在一个装饰器上实现不可变类的某些行为。我想要一个从namedtuple继承的类(具有属性不变性),并且还想添加一些新方法。像这样 ...但是正确防止将新属性分配给新类。

从namedtuple继承时,应定义__new__并设置__slots__为空元组(以保持不变性):

def define_new(clz):
    def __new(cls, *args, **kwargs):
        return super(clz, cls).__new__(cls, *args, **kwargs)

    clz.__new__ = staticmethod(__new) # delegate namedtuple.__new__ to namedtuple
    return clz

@define_new
class C(namedtuple('Foo', "a b c")):
    __slots__ = () # Prevent assignment of new vars
    def foo(self): return "foo"

C(1,2,3).x = 123 # Fails, correctly
Run Code Online (Sandbox Code Playgroud)

太好了 但是现在我想将__slots__任务移到装饰器中:

def define_new(clz):
    def __new(cls, *args, **kwargs):
        return super(clz, cls).__new__(cls, *args, **kwargs)

    #clz.__slots__ = ()
    clz.__slots__ = (123) # just for testing

    clz.__new__ …
Run Code Online (Sandbox Code Playgroud)

python decorator class-method namedtuple

0
推荐指数
1
解决办法
159
查看次数