我想知道,处理抽象属性类型验证的最佳实践是什么?
from abc import ABC, abstractmethod
class Base(ABC):
@property
@abstractmethod
def name(self):
"""
:type str
"""
pass
class MyClass(Base):
name = 1 # TypeError
不是那么简单,但是可以这样:
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
使用__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