考虑下面的代码
from abc import ABC, ABCMeta
class MyMetaClass(ABCMeta):
@property
def metaclass_property(cls):
return "result"
# def __dir__(cls):
# return list(super().__dir__()) + ['metaclass_property']
class MyBaseClass(ABC, metaclass=MyMetaClass):
@classmethod
@property
def baseclass_property(cls):
return "result"
class MyClass(MyBaseClass, metaclass=MyMetaClass):
pass
assert MyClass.baseclass_property == "result"
assert hasattr(MyClass, 'baseclass_property')
assert 'baseclass_property' in dir(MyClass)
assert MyClass.metaclass_property == "result"
assert hasattr(MyClass, 'metaclass_property')
assert 'metaclass_property' in dir(MyClass)
我注意到这在最后一行抛出了一个断言错误。(python v3.9.6)。为什么呢?是虫子吗?可以通过按照两个未注释行将其手动添加到__dir__
来修复它
我的问题是,解决这个问题的最好办法是什么?classmethod属性和元类属性之间有什么根本区别吗?(即,是否有我能做或不能做的事情,但不能做其他事情?)
我认为这与属性、元类或
abc
无关一个简单的例子:
在本例中,
object
是int
的基类,而type
是int
的元类dir
函数的official documentation明确表示及
及
相关问题 更多 >
编程相关推荐