简体   繁体   English

无法将属性类型设置为自定义 class 列表

[英]Unable to set type of property to list of custom class

I'm trying to set the type of one of the properties in this custom class to a list of another custom class and it's not allowing me to do so.我正在尝试将此自定义 class 中的一个属性的类型设置为另一个自定义 class 的列表,但它不允许我这样做。 I've tried both List and Sequence , but neither have allowed me to do this.我已经尝试过ListSequence ,但都不允许我这样做。 Am I misunderstanding how typings are supposed to be used?我是否误解了应该如何使用类型?

from models import ClassificationAttributeConstraint, ClassificationAttributeRatioConstraint, ValueAttributeConstraint, PortfolioConstraint
from typing import List


class OptimizerInput:

    case_id: int
    job_type: str
    frequency: int
    risk_aversion: float
    frontier_point: int
    classification_attribute_constraints: List[ClassificationAttributeConstraint]

    def __init__(self, case_id: int = None, job_type: str = None, frequency: int = None, risk_aversion: float = None,
                 frontier_point: int = None, classification_attribute_constraints: List[ClassificationAttributeConstraint] = None):
        self.case_id = case_id
        self.job_type = job_type
        self.frequency = frequency
        self.risk_aversion = risk_aversion
        self.frontier_point = frontier_point
        self.classification_attribute_constraints = classification_attribute_constraints

TypeError: Parameters to generic types must be types. Got <module 'models.ClassificationAttributeConstraint' from 'C:\\Users\\<removed>

The problem is with the import statement, ClassificationAttributeConstraint in your case is a module, since the folder structure is:问题在于import语句,您的情况下的ClassificationAttributeConstraint是一个模块,因为文件夹结构是:

module/
    myscript.py
    models/
        __init__.py
        ClassificationAttributeConstraint.py
        ...

So, you need to import the class itself from that module:因此,您需要从该模块导入 class 本身:

from models.ClassificationAttributeConstraint import ClassificationAttributeConstraint

And it should work just fine它应该工作得很好

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM