简体   繁体   中英

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. I've tried both List and Sequence , but neither have allowed me to do this. 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:

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

So, you need to import the class itself from that module:

from models.ClassificationAttributeConstraint import ClassificationAttributeConstraint

And it should work just fine

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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