簡體   English   中英

將類屬性類型從字符串更改為 int

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM