[英]How to create class object without __dict__
class B(type):
__slots__ = ()
class A(metaclass=B):
pass
A.test = "test"
"A"
is instance of metaclass "B"
and "B"
have __slots__
defined - why I have __dict__
at class A
? "A"
是元类"B"
实例, "B"
是__slots__
定义的 - 为什么我在A
类有__dict__
? How I can create class object without __dict__
? 如何在没有__dict__
情况下创建类对象?
You cannot do this; 你不能做这个; classes always have a __dict__
. 类总是有一个__dict__
。
You can only use __slots__
on classes to produce instances without a __dict__
, not on meta types. 您只能在类上使用__slots__
来生成没有__dict__
实例,而不是元类型。 You'd normally only produce a few classes, so there is not much point in supporting __slots__
on metaclasses. 您通常只生成一些类,因此在元类上支持__slots__
没有多大意义 。
Don't use __slots__
to prevent attributes being set. 不要使用__slots__
来防止设置属性。 Use __setattr__
for that instead: 改为使用__setattr__
:
class NoAttributesClassMeta(type):
def __setattr__(cls, name, value):
if name not in cls.__dict__:
raise AttributeError("Cannot set attributes")
type.__setattr__(cls, name, value)
__slots__
won't stop you from setting an attribute to a class, you need to override __setattr__
for that. __slots__
不会阻止您将属性设置为类,您需要覆盖__setattr__
。 Something like this should do it: 这样的事情应该这样做:
class B(type):
def __new__(cls, clsname, bases, dct):
dct['__slots__'] = ('x',)
return type.__new__(cls, clsname, bases, dct)
def __setattr__(cls, attr, val):
if attr not in cls.__slots__:
raise AttributeError('Can\'t set {!r}'.format(attr))
else:
type.__setattr__(cls, attr, val)
class A(metaclass=B):
pass
Demo: 演示:
>>> A.x = 1
>>> A.y = 2
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
A.y = 2
File "C:\Python27\so.py", line 7, in __setattr__
raise AttributeError('Can\'t set {!r}'.format(attr))
AttributeError: Can't set 'y'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.