[英]Change class attribute type from string to int
我有一个应该用所有参数int
初始化的类,但有时它会得到string
而不是int
@dataclass
class Meth:
one: Optional[int] = None
two: Optional[int] = None
three: Optional[int] = None
my_class = Meth(one="1",two=2,three=None)
正如您在属性one
中看到的那样,类型不好。 为了解决这个问题,我的第一个想法是像这样再次创建它
new_class = Meth(one=int(my_class.one),two=int(my_class.two),three=int(my_class.three)
但我收到此错误,因为三个是无
TypeError: int() argument must be a string, a bytes-like object, or a real number, not 'NoneType'
所以我的问题是将所有属性类型更改为正确类型的最佳方法是什么。
该错误是在将 None 转换为 int 时引起的,而不是因为指定的类型。 您可以添加支票:
new_class = Meth(
one=int(my_class.one),
two=int(my_class.two),
three=my_class.three if my_class.three is None else int(my_class.three)
)
更好的方法是在初始化类时这样做
class Meth:
one: int = None
def __init__(self,
one: Optional[Union[str,int]] = None,
two: Optional[int] = None,
three: Optional[int] = None):
# Do the checks and assign values
if one is not None:
self.one = int(one)
或者通过使用库进行数据验证,pydantic 或类似的:
from pydantic import BaseModel
class Meth(BaseModel):
one: int
two: Optional[int]
three: Optional[int]
my_class = Meth(one="1",two=2,three=None)
assert type(my_class.one) is int
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.