如何在没有__dict__的情况下创建类对象 [英] How to create class object without __dict__
问题描述
class B(type):
__slots__ = ()
class A(metaclass=B):
pass
A.test = "test"
"A"
是元类"B"
的实例,并且"B"
定义了 __ slots __
-为什么我在 A
类中有 __ dict __
吗?如何在没有 __ dict __
的情况下创建类对象?
"A"
is instance of metaclass "B"
and "B"
have __slots__
defined - why I have __dict__
at class A
? How I can create class object without __dict__
?
推荐答案
您无法执行此操作;类始终具有 __ dict __
.
You cannot do this; classes always have a __dict__
.
您只能在类上使用 __ slots __
来生成没有 __ dict __
的实例,而不能在元类型上使用.通常,您只生成几个类,因此在元类上支持 __ slots __
的意义不大.
You can only use __slots__
on classes to produce instances without a __dict__
, not on meta types. You'd normally only produce a few classes, so there is not much point in supporting __slots__
on metaclasses.
请勿使用 __ slots __
来防止设置属性.请改用 __ setattr __
:
Don't use __slots__
to prevent attributes being set. Use __setattr__
for that instead:
class NoAttributesClassMeta(type):
def __setattr__(cls, name, value):
if name not in cls.__dict__:
raise AttributeError("Cannot set attributes")
type.__setattr__(cls, name, value)
这篇关于如何在没有__dict__的情况下创建类对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!