是否可以生成namedtuple
从基类继承的 a?
我想要的是Circle
and Rectangle
are namedtuple
s 并且是从一个公共基类 ('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)
我该怎么做?
我正在一个装饰器上实现不可变类的某些行为。我想要一个从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)