python - 在创建对象类 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 和对象不太确定我将如何去做。
感谢您的时间和提前帮助:)
解决方案
除了 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
。文档可以在这里找到。
推荐阅读
- r - 检查条件异方差
- java - 引起:io.lettuce.core.RedisCommandExecutionException: MOVED 8731 172.19.122.164:6379
- laravel - 使用 Nuxt 在 Laravel 上调用 null 上的成员函数 store()
- python - Python virtualenv pip install 给出 ssl 错误
- azure - 创建 API 以对用户进行身份验证以访问 Azure Active Directory
- javascript - 为什么子行打不开?在数据表中
- javascript - 如何将字符串添加到待办事项列表中的字符串列表中
- unity3d - Unity Header 属性无法正常工作
- matlab - 为什么 Psychtoolbox 中的 KbCheck 没有注册键盘输入?
- ruby-on-rails - 如何使用 rspec 禁用 rswag 文件的测试,但仅将它们用于文档?