首页 > 解决方案 > 静态嵌套类可以是 Python 3 中外部类的子类吗?

问题描述

我创建了一个类来存储 TF-IDF 矩阵生成的设置。

class TFIDF_settings:
    max_features = 5000
    
    class word_level(TFIDF_settings):
        analyzer = "word"
        ngram_range = (1,1)
    
    class ngram_level(TFIDF_settings):
        analyzer = "word"
        ngram_range = (2,3)

我希望该属性TFIDF_settings.max_feature能够顺利传递给所有内部类 -print(TFIDF_settings.word_level.max_features)应该返回5000

正如您在代码中看到的那样,我认为继承外部类可以完成这项工作,但它会抛出一个NameError.

<ipython-input-18-0ddd9158decc> in TFIDF_settings()
      2     max_features = 5000
      3 
----> 4     class word_level(TFIDF_settings):
      5         analyzer = "word"
      6         ngram_range = (1,1)

NameError: name 'TFIDF_settings' is not defined

有没有办法(最好是隐式地)将max_features外部类的属性传递给内部类?

标签: pythonpython-3.xoop

解决方案


推荐阅读