[Python] How to denote return type of a @classmethod ctor in python?

Discussão em 'Python' iniciado por Stack, Maio 11, 2025.

  1. Stack

    Stack Membro Participativo

    #!/usr/bin/env python

    # In this file: a problem with de-serializing an object.

    import pickle

    class User:
    @classmethod
    def from_bytes(cls, b: bytes) -> User:
    obj = pickle.loads(b)
    assert type(obj) == cls, (type(obj), cls)
    return obj


    fails with

    Traceback (most recent call last):
    File "/tmp/./lqlq.py", line 7, in <module>
    class User:
    ...<4 lines>...
    return obj
    File "/tmp/./lqlq.py", line 9, in User
    def from_bytes(cls, b: bytes) -> User:
    ^^^^
    NameError: name 'User' is not defined


    In C you do a forward declaration. What's the alternative in python?

    Continue reading...

Compartilhe esta Página