如何在Python中强制函数参数类型?

13 投票
2 回答
39218 浏览
提问于 2025-04-17 15:46

我在一个Python类里有个函数,可以把接口添加到一个列表里。

def RegisterAsListener(self, inListener):
    self.__TransitListeners.append(inListener)

这样做挺好的,因为一个类只需要继承这个我的接口,拿到这个对象,然后注册自己来接收所有的更新。

class ITransit():
    def TransitUpdate(self, data):
        raise NotImplementedError("You must define this function.")

(假设我正确地创建了一个接口)

因为这个项目不是我一个人在做,我不想让别人用错误的数据类型来调用RegisterAsListener这个函数。我可以在注册函数里加代码来检查数据类型,但如果编译器在他们试图传入错误的数据类型时直接给程序员报错,那就简单多了。

def RegisterAsListener(self, IListener inListener):
    self.__TransitListeners.append(inListener)

有没有什么办法可以做到这一点?

2 个回答

7

因为这个项目不是我一个人在做,我不想让其他人用错误的数据类型去调用 RegisterAsListener 这个函数。

要对这个函数进行详细的说明文档,这样如果有人传入错误的参数,就会抛出异常。使用 RegisterAListener 的人应该能通过文档了解到这个函数需要什么样的数据。如果传入了错误的参数,抛出的异常应该能清楚地告诉 RegisterAListener 的使用者他们哪里出错了。

8

虽然我强烈建议不要这样做,最好是通过抽象基类来强制实现某些方法(你可以查看这个链接了解更多: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

撰写回答