Python元类-使类属性可通过类和类实例访问

问题描述 投票:3回答:1

使用python 3.7,我在元类中创建了一个类属性。我希望能够通过类本身或该类的实例化对象访问属性。我可以通过创建一个类属性和一个实例属性来模拟它,但是它带有PyCharm的类型提示。这是我认为理想的设置:

class Meta(type):
    @property
    def cls_prop(cls) -> str:
        return 'foo'


class A(metaclass=Meta):
    pass

但是很遗憾,这里是结果:

>>> A.cls_prop
'foo'
>>> a = A()
>>> a.cls_prop
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'A' object has no attribute 'cls_prop'

向调用类属性的A添加实例属性在运行时有效,但是PyCharm的类型自省会引起混淆(它开始将A.cls_prop视为property而不是str):

class A(metaclass=Meta):
  @property
  def cls_prop(self) -> str:
      return self.__class__.cls_prop

>>> A.cls_prop
'foo'
>>> a = A()
>>> a.cls_prop
'foo'

有更好的方法吗?

python pycharm metaclass type-hinting
1个回答
0
投票

我认为使用父类可以更好地完成您想做的事情:

class Parent:
    @property
    def cls_prop(self):
        return 'foo'

class A(Parent):
    pass

>>> a = A()
>>> a.cls_prop
'foo'
>>>> A.cls_prop
<property object at 0x7f1afcb190e8>

[如果您还希望能够直接在类上访问A.cls_prop(即,无需创建实例),则可能需要查看另一个问题:@staticmethod with @property

© www.soinside.com 2019 - 2024. All rights reserved.