Python:抽象属性类型验证

问题描述 投票:0回答:2

我想知道,处理抽象属性类型验证的最佳实践是什么?

from abc import ABC, abstractmethod

class Base(ABC):

    @property
    @abstractmethod
    def name(self):
       """
       :type str
       """
       pass

class MyClass(Base):
    name = 1    # TypeError
python python-3.x oop abstract-class abstract
2个回答
0
投票

不是那么简单,但是可以这样:

from abc import ABC, abstractmethod

class Base(ABC):

    @property
    @abstractmethod
    def name(self):
        raise NotImplementedError("To be provided in derived classes")

class AClass(Base):
    def __init__(self):
        self._name = ""

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, value):
        if type(value) is not str:
            raise ValueError("Only string is allowed")
        self._name = value

a = AClass()
a.name = "hello" # no error
a.name = 1       # raises a value error


0
投票

使用__init_subclass__。您根本不会name成为抽象或其他形式的属性。

class Base:

    def __init_subclass__(cls, *args, **kwargs):
       super().__init_subclass__(**kwargs)
       if not isinstance(cls.name, str):
           raise TypeError(f'{cls.name} is not a string value')


class MyClass(Base):
    name = 1
© www.soinside.com 2019 - 2024. All rights reserved.