Python 3.9元类属性与Classmethod属性

2024-09-28 22:22:43 发布

您现在位置:Python中文网/ 问答频道 /正文

考虑下面的代码

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属性和元类属性之间有什么根本区别吗?(即,是否有我能做或不能做的事情,但不能做其他事情?)


Tags: returndefdirmyclasspropertyassertresultclass
1条回答
网友
1楼 · 发布于 2024-09-28 22:22:43

我认为这与属性、元类或abc无关

一个简单的例子:

>>> int.__mro__
(<class 'int'>, <class 'object'>)
>>> isinstance(int, type)
True
>>> '__mro__' in dir(int)
False
>>> '__mro__' in dir(type)
True

在本例中,objectint的基类,而typeint的元类

dir函数的official documentation明确表示

attempts to produce the most relevant, rather than complete, information

If the object is a type or class object, the list contains the names of its attributes, and recursively of the attributes of its bases.

metaclass attributes are not in the result list when the argument is a class

相关问题 更多 >