AZW
AZW

Reputation: 63

Can I make class method in Python to take argument in type of this class?

I want to specify, that some method takes argument in same type, like this function.

I try to explain by example of animals

class Animal:
    def __init__(self, name : str):
        self.name = name

    def say_hello(self, animal: Animal):
        print(f"Hi {animal.name}")

name with type str doesn't make any problems, but Animal is not recognized:

NameError: name 'Animal' is not defined

I use PyCharm and Python 3.7

Upvotes: 2

Views: 47

Answers (2)

Norrius
Norrius

Reputation: 7920

The class name is not available because it is not yet defined at this point. Since Python 3.7, you can enable postponed evaluation of annotations (PEP 563) by adding this line before any imports or code:

from __future__ import annotations

Alternatively, you can use string annotations, which should be recognised by most type checkers, including the one built into PyCharm:

class Animal:
    def __init__(self, name: str):  # this annotation can be left as a class
        self.name = name

    def say_hello(self, animal: 'Animal'):  # this one is itself a string
        print(f"Hi {animal.name}")

Upvotes: 1

gmds
gmds

Reputation: 19885

Define a type with typing.NewType and inherit from it:

from typing import NewType

AnimalType = NewType('AnimalType', object)

class Animal:
    def __init__(self, name: str):
        self.name = name

    def say_hello(self, animal: AnimalType):
        print(f"Hi {animal.name}")

Upvotes: 0

Related Questions