检查参数类型的Pythonic方法 [英] Pythonic Way To Check for A Parameter Type

查看:134
本文介绍了检查参数类型的Pythonic方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个小项目的工作,并已经做了一些类和方法。其中一个类代表我们库存中的货架,另一个代表货架上的每个货架。我有一个方法来添加一个新的bin到货架上,我添加了一些逻辑,以确保它被传递一个Location对象,然后将其添加到货架(现在我使用列表,而我开发之前,把一切移到一个数据库)。



然而,我只是在一本Python书中读到,我通常最好处理异常,而不是添加额外的代码。我删除了逻辑,看看会得到什么错误,但我没有得到任何东西,它允许一个字符串代替Location对象。



有更多的Pythonic方法

 <$> 



c $ c> class CrossDock:
locations = []

def add_location(self,location):
if isinstance(location,Location):#if this is commented out it将需要传递给它的
self.locations.append(location)
else:
print(location参数必须是type:Location。参数是类型+ str类型(位置)))

有一种方法,我可以用try / except块吗?

解决方案

向调用者传播异常。这会迫使您的类别的用户在他们滥用课程时修复无效类型。打印无效,因为它不强制执行接口合约。

  class CrossDock(object):
def __init __ self):
self.locations = []

def add_location(self,location):
if isinstance(location,Location):
self.locations.append (位置)
else:
raise TypeError(location必须是Location,got:+
repr(type(location)))
/ pre>

I'm working on a little side project for work and have made some classes and methods. One of the classes represents a shelf in our inventory and another represents each a bin on the shelf. I have a method to add a new bin to the shelf and I added some logic to make sure it was passed a Location object before it is added to the shelf (right now I'm using lists while I develop before moving everything to a DB).

However I just read in a Python book that I have that it is usually better to handle exceptions as they arise rather than add extra code. I removed the logic to see what error I would get but I didn't get anything it allowed a string in place of the Location object.

Is there a more Pythonic way to enforce what type a parameter is?

What I have for the shelf:

class CrossDock:
locations = []

def add_location(self, location):
    if isinstance(location, Location): #if this is commented out it will take what ever is passed to it
        self.locations.append(location)
    else:
        print("location parameter must be of type: Location. Parameter is of type" + str(type(location)))

Is there a way I can do this with a try/except block?

解决方案

Propagate an exception to the caller. This forces users of your class to fix the invalid type when they misuse the class. Printing is not useful as it does not enforce an interface contract.

class CrossDock(object):
    def __init__(self):
        self.locations = []

    def add_location(self, location):
        if isinstance(location, Location):
            self.locations.append(location)
        else:
            raise TypeError("location must be Location, got: " +
                            repr(type(location)))

这篇关于检查参数类型的Pythonic方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆