下面的脚本试图从类Inner1
中删除Outer
嵌套类。我收到明确的错误“ TypeError:无法删除__class__属性”。死胡同?
def Loader(cls):
for key in dir(cls):
value = getattr(cls, key)
if isinstance(value, type):
delattr(cls, key)
return cls
@Loader
class Outer:
class Inner1:
X = 1
print(Outer.Inner1.X)
答案 0 :(得分:1)
问题是以下行:
if isinstance(value, type):
匹配从type
继承的所有内容。如果您只希望删除在装饰类中显式定义的内部类,则可以使用以下内容:
from inspect import isclass
def Loader(cls):
# vars returns the __dict__ attributes, so only names that are explicitely defined in cls.
for key, value in vars(cls).copy().items():
# If it is a class, delete it
if isclass(value):
delattr(cls, key)
return cls
@Loader
class Outer:
class Inner1:
X = 1
print(Outer.Inner1.X) # AttributeError: type object 'Outer' has no attribute 'Inner1'
另一种选择是使装饰器成为一个类,并明确告诉您要删除的名称。例如
class Loader:
def __init__(self, *args):
# Store the given names to delete
self.names = args
def __call__(self, cls):
for name in self.names:
try:
delattr(cls, name)
except AttributeError:
pass
return cls
@Loader('Inner1', 'Inner2', 'etc')
class Outer:
class Inner1:
X = 1
print(Outer.Inner1.X) # AttributeError: type object 'Outer' has no attribute 'Inner1'
也就是说,我不确定为什么要装饰一个类并定义要动态删除的内部类……为什么不……根本不定义它们? :D