我试图在元类中使用property()来提供访问/设置内部属性的方法。我使用property()作为@property的名称,因为它在元类中,我需要将该属性应用于在__new__方法中传递的类。在
这是我的代码和相关部分的基本示例:def __new__(mcls, name, bases, dct, **kwargs):
def getabstract(obj):
return getattr(obj, '_abstract', False)
def setabstract(obj, value):
if str(value) in ('True', 'False'):
return setattr(obj, '_abstract', value)
else: print(f'invalid abstract assignment {value}')
return None
cls = super().__new__(mcls, name, bases, dct)
for name, value in cls.__dict__.items():
if callable(value):
# only applies to callable (method)
value._abstract = getattr(value, '_abstract', False)
# add an _abstract attribute to the method or return its
# current value if it already has one
for base in bases:
base._abstract = getattr(base, '_abstract', False)
# give each base class an _abstract attribute if not already given
cls.abstract = property(getabstract(cls),
setabstract(cls, getattr(cls, '_abstract', False)))
# make an abstract property for class
for name, value in cls.__dict__.items():
if callable(value):
# make an abstract property for functions
value.abstract = property(getabstract(value),
setabstract(value, getattr(value, '_abstract', False)))
当我运行这个时,不会发生错误,但是当访问这个元类创建的新类时,它返回:
^{pr2}$
另外,用作setter的setabstract()函数只设置True或{}的属性,但是当我执行类似Foo.abstract = 'foo'的操作时,它仍然将值设置为'foo'
是我做错了什么还是错过了什么?在