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

标签 python python-2.7 elasticsearch

我正在使用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/

相关文章:

python-2.7 - 如何使用非 ASCII 字符?

python - 如何在 Windows 上安装 PyQt4?

elasticsearch - 带有分组query_string的Elasticsearch

c# - 如何使用C#Nest 2.0从ElasticSearch响应中查看API查询

elasticsearch - 如何使用Elasticsearch在查询中使用特殊命令进行搜索?

Python xml ElementTree : find values of only first 3 elements with same name

python - 类型错误 : unhashable type: 'list' (a few frames into program)

python - 在Python 3中进行精确的浮点除法

python - 函数内部多处理 scipy 优化的奇怪行为

python - 在 csv 中写入 unicode 数据