ID EN
Typing

Self

Python 3.11 🇮🇩 Bahasa Indonesia

Tipe khusus untuk mewakili kelas tertutup saat ini.

Syntax

PYTHON
typing.Self

Contoh

Example 1
PYTHON
from typing import Self, reveal_type

class Foo:
    def return_self(self) -> Self:
        ...
        return self

class SubclassOfFoo(Foo): pass

reveal_type(Foo().return_self())   Revealed type is "Foo"
reveal_type(SubclassOfFoo().return_self())   Revealed type is "SubclassOfFoo"
Example 2
PYTHON
from typing import TypeVar

Self = TypeVar("Self", bound="Foo")

class Foo:
    def return_self(self: Self) -> Self:
        ...
        return self
Example 3
PYTHON
class Eggs:
     Self would be an incorrect return annotation here,
     as the object returned is always an instance of Eggs,
     even in subclasses
    def returns_eggs(self) -> "Eggs":
        return Eggs()

See Also

classmethod __enter__()