gpt4 book ai didi

python - 我可以从外部类的类方法中调用内部类吗?

转载 作者:行者123 更新时间:2023-11-30 22:13:30 28 4
gpt4 key购买 nike

我正在使用elasticsearch_dsl库,但这个问题广泛适用于python。

我想定义一个方法来创建名为:test__YYYY-MM-DD

class Test(DocType):
content = Text()

class Meta:
index = 'test'

@classmethod
def create_index(cls):
now = datetime.datetime.utcnow().strftime('%Y-%m-%d')
test = Index('{}__{}'.format(cls.Meta.index, now))
^^^ this does not exist
test.doc_type(cls)
test.create()

如何访问位于 Meta 内部类中的 index 字段?

最佳答案

I'm working with the elasticsearch_dsl library but this question is broadly applicable to Python.

实际上,它并不广泛适用于 Python。在普通的类中,访问 cls.Meta.index 会像往常一样工作。 DocType has a metaclassremoves Meta from the class namespace 。如果我正确阅读源代码,您要查找的属性应该可以在 cls._doc_type.index 处找到。

>>> class Example(DocType):
... class Inner:
... index = 'inner_var'
... class Meta:
... index = 'meta_var'
... @classmethod
... def foo(cls):
... print(cls.Inner.index)
... print(cls._doc_type.index)
...
>>> Example.foo()
inner_var
meta_var

注意:DocTypeOptions 实例上存在前导下划线,即 _doc_type,表明是私有(private) API。也许您应该寻找公共(public) API 来创建索引。

关于python - 我可以从外部类的类方法中调用内部类吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50769603/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com