Can you annotate return type when value is instance of cls?

前端 未结 3 545
闹比i
闹比i 2020-11-29 04:55

Given a class with a helper method for initialization:

class TrivialClass:
    def __init__(self, str_arg: str):
        self.string_attribute = str_arg

            


        
3条回答
  •  时光取名叫无心
    2020-11-29 05:23

    From Python 3.7 you can use __future__.annotations:

    from __future__ import annotations
    
    
    class TrivialClass:
        # ...
    
        @classmethod
        def from_int(cls, int_arg: int) -> TrivialClass:
            # ...
            return cls(...)
    
    

    Edit: you can't subclass TrivialClass without overriding the classmethod, but if you don't require this then I think it's neater than a forward reference.

提交回复
热议问题