简体   繁体   中英

What is the best generic type hint for a dataclass in python?

I have started using dataclasses and I have some specific one lets say for example:

from dataclasses import dataclass

@dataclass
class Person:
    name: str
    age: int
    job:str
    
@dataclass
class Animal:
    name: str
    age: int

I then have an abstract class like an interface

import abc
from typing import List, Dict


class NameFinder:
    @abc.abstractmethod
    def get_name(self, name: str,being ) :
        pass

class PersonName(NameFinder):
    def get_name(self, name:str, person:Person):
        return person.name

class AnimalName(NameFinder):
    def get_name(self, name:str, animal:Animal):
        return animal.name

what is a good generic type hint i can use in the abstract class as placeholder for both the Person and the Animal classes?

You can define a protocol class, which just asserts the existence of a name attribute.

from typing import Protocol


class Named(Protocol):
    name: str


class NameFinder:
    @staticmethod
    def get_name(obj: Named) -> str:
        return obj.name

# or ...
def name_finder(obj: Named) -> str:
    return obj.name

get_name and name_finder can both accept arguments of type Person or Animal , as both classes define a name attribute for their instances. There's no need to explicitly mark the classes as implementing the Named protocol.

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