I have a function in a Python class that adds Interfaces to a list.

我在Python类中有一个函数,它将接口添加到列表中。

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

This is nice, because a class just needs to inherit from said my Interface, grab this object, and register itself for all updates.

这很好,因为类只需要从said my Interface继承,获取这个对象,并为所有更新注册自己。

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

(assuming I made an interface correctly)

(假设我做的界面是正确的)

Since i'm not the only one on this project, I don't want somebody calling the RegisterAsListener function with an incorrect data type. I could put in code to check the type within the register function, but it would be easier all around if the compiler just yelled at the programmer when they try to shove in an incorrect data type.

因为我不是这个项目中唯一的一个,我不希望有人用不正确的数据类型调用RegisterAsListener函数。我可以输入代码来检查寄存器函数中的类型,但是如果编译器在试图插入不正确的数据类型时对程序员大声叫骂,那就更容易了。

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

Is there any way to do this?

有什么办法吗?

2 个解决方案

#1


6

Although I would strongly recommend not doing this and only enforcing the implementation of certain methods using Abstract Base Classes (http://docs.python.org/2/library/abc.html), it is possible.

尽管我强烈建议不要这样做,只使用抽象基类(http://docs.python.org/2/library/abc.html)强制实现某些方法,但这是可能的。

Here's an example on how to do something like that: http://www.artima.com/weblogs/viewpost.jsp?thread=101605

这里有一个如何做这样事情的示例:http://www.artima.com/weblogs/viewpost.jsp?

# 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__

And the code using it:

以及使用它的代码:

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)

Example output:

示例输出:

Calling the int method
<type 'int'>: 5
Calling the float method
<type 'float'>: 5.0

更多相关文章

  1. python cookboo 文件与IO 函数
  2. Python(名称空间、函数嵌套、函数对象)
  3. python中函数参数传递的几种方法
  4. python函数篇0-2
  5. Python的范围函数如何工作?
  6. Python日期和时间函数
  7. python的接口实现zope.interface示例
  8. Python入门:内置函数
  9. Python测试函数和类 笨方法学习Python

随机推荐

  1. Android资源文件中特殊字符未转义引起的
  2. android中UI主线程与子线程深入分析
  3. Android系统更新历史(系统和名称)
  4. Android上跑OpenCV
  5. Android(安卓)RecyclerView之添加Item分
  6. 安卓自动生成代码插件-Android(安卓)code
  7. [安卓基础] Android自定义shape
  8. android保存文件到SD卡中
  9. 最新Android框架排行榜,上百项资源汇总!
  10. Android工程引用其他项目