首页 > 解决方案 > 在创建对象类 Python 时,如何确保用户输入正确的类型(在我的例子中是列表)

问题描述

嗨,我试图在创建新类对象时检查输入以确定它们是否输入正确,如果说“theMoves”输入不正确,则执行诸如忽略它或尝试将其转换为列表之类的操作。

Class Card:
    def __init__(self, theName,theHP, theMoves ):
        self.theName=str(theName)       
        self.theHp=int(theHP)
        self.theMoves=theMoves # [(),()..]


Class Deck:
#more code here
#When i try adding a card to the deck i get an index error because theMoves in the Card class arnt correct. It works with the c0,c1

def main():
    #c0=Card("Dave",454,[("Fieball",999)]) # works
    c1=Card("Bob",500,[("Fireball",999),("Flame",999),("Waterblast",499)]) #works
    #c2=Card("Peter",400,(fire,342))  # Fix 
    #c3=Card("Josh",300,waterb,22) #fix (maybe by just ignoring the moves after checking each varible)

我想知道是否有一种方法可以让如果有人输入的信息不正确,就像我在“c2”/“c3”中所做的那样,那么它应该转换值以匹配 c0 或 c1 等格式,或者只是忽略所有值。如果它更容易,我不介意如果输入错误则忽略 theMove 值,但我不知道该怎么做?当我在网上查看时,我看到有人提到了方法,但我对 python 和对象不太确定我将如何去做。

感谢您的时间和提前帮助:)

标签: python

解决方案


除了 using 之外isinstance(),您还可以使用类型提示,它提供了更多的语法糖。

from typing import List, Tuple
def __init__(self, theName: str, theHP: int, theMoves: List[Tuple[str, int]]):
    self.theName = theName
    self.theHp = theHP
    self.theMoves = theMoves

如您所见,语法比使用isinstance().

如果出现导入​​错误,您可以使用 pip: 安装/升级官方模块pip install --upgrade typing。文档可以在这里找到。


推荐阅读