Skip to main content
 首页 » 编程设计

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

2024年11月01日11kuangbin

我在 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 检查?是否有一种方便的鸭子类型检查可以捕获所有失败)。