Python:抽象属性类型验证
Python: abstract property type validation
我想知道,处理抽象 属性 类型验证的最佳做法是什么?
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
我想知道,处理抽象 属性 类型验证的最佳做法是什么?
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