gpt4 book ai didi

python - 如何修复 Python 中错误类型的对象?

转载 作者:太空宇宙 更新时间:2023-11-04 03:54:37 25 4
gpt4 key购买 nike

我在 Python 3 中开发,我有一个方法,它的参数是我的 Color 类,但是当我尝试使用一种方法:

def __init__(self, name, color=Color.Color("none"), style="solid", width="1px"):
self.__name = name
self.__style = style
self.__width = width
if color.get_name() == "none":
color.color_by_name('Black')

这是错误:

File ................, line 10, in __init__
if color.get_name() == "none":
AttributeError: 'str' object has no attribute 'get_name'

最佳答案

听起来您想接受 Color 对象或字符串。您可以鸭式输入或显式检查:

鸭型:

def __init__(self, name, color=Color.Color("Black"), style="solid", width="1px"):
# Note: Changed default to 'Black', since there is no color 'none'
# This makes it a lot simpler.
self.__name = name
self.__style = style
self.__width = width
try:
color.get_name()
except AttributeError:
color = Color.Color(color)

显式检查:

def __init__(self, name, color=Color.Color("Black"), style="solid", width="1px"):
self.__name = name
self.__style = style
self.__width = width
if not isinstance(color, Color.Color):
color = Color.Color(color)

两种方法都行;哪个更容易取决于您的检查的确定性(即您是否有其他类,如颜色需要单独的 isinstance 检查?是否有一种方便的鸭子类型检查可以捕获所有失败)。

关于python - 如何修复 Python 中错误类型的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19547248/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com