[英]Force a function parameter type in Python?
我在 Python 类中有一个函数,可以将接口添加到列表中。
def RegisterAsListener(self, inListener):
self.__TransitListeners.append(inListener)
这很好,因为一个类只需要从我的接口继承,获取这个对象,并为所有更新注册自己。
class ITransit():
def TransitUpdate(self, data):
raise NotImplementedError("You must define this function.")
(假设我正确制作了一个界面)
由于我不是这个项目中唯一的一个,我不希望有人使用不正确的数据类型调用 RegisterAsListener 函数。 我可以输入代码来检查 register 函数中的类型,但是如果编译器在程序员试图输入不正确的数据类型时只是对他们大喊大叫,那么一切都会更容易。
def RegisterAsListener(self, IListener inListener):
self.__TransitListeners.append(inListener)
有没有办法做到这一点?
尽管我强烈建议不要这样做,而只使用抽象基类 ( http://docs.python.org/2/library/abc.html ) 强制实施某些方法,但这是可能的。
这是一个关于如何做这样的事情的例子: http : //www.artima.com/weblogs/viewpost.jsp?thread=101605
# mm.py
registry = {}
class MultiMethod(object):
def __init__(self, name):
self.name = name
self.typemap = {}
def __call__(self, *args):
types = tuple(arg.__class__ for arg in args) # a generator expression!
function = self.typemap.get(types)
if function is None:
raise TypeError("no match")
return function(*args)
def register(self, types, function):
if types in self.typemap:
raise TypeError("duplicate registration")
self.typemap[types] = function
def multimethod(*types):
def register(function):
function = getattr(function, "__lastreg__", function)
name = function.__name__
mm = registry.get(name)
if mm is None:
mm = registry[name] = MultiMethod(name)
mm.register(types, function)
mm.__lastreg__ = function
return mm
return register
if hasattr(function, "__lastreg__"):
function = function.__lastreg__
以及使用它的代码:
import mm
@mm.multimethod(int)
def spam(a):
print 'Calling the int method'
print '%s: %r' % (type(a), a)
@mm.multimethod(float)
def spam(a):
print 'Calling the float method'
print '%s: %r' % (type(a), a)
spam(5)
spam(5.0)
示例输出:
Calling the int method
<type 'int'>: 5
Calling the float method
<type 'float'>: 5.0
由于我不是这个项目中唯一的一个,我不希望有人使用不正确的数据类型调用 RegisterAsListener 函数
彻底记录函数,然后让不正确的参数抛出异常。 RegisterAListener
的用户应该能够使用文档来了解函数需要什么样的数据,并且 - 如果给定的参数不正确 - 产生的异常应该清楚RegisterAListener
的用户做错了什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.