是否可以在Python中检测冲突的方法名称?

And*_*een 5 python inheritance multiple-inheritance python-2.x

我创建了一个名为的Python类Liger,它扩展了名为Lion和的类Tiger。该类从和都Liger继承了该方法,但是语法仍然有效-不会显示任何错误消息,但该方法的实现由继承。是否可以在Python中检测到这样的方法名冲突,以便当方法名发生这种冲突时会打印一条错误消息?speak()LionTigerTigerspeak()Liger

'''
Conflicting method names in python
'''


class Tiger():
    @staticmethod
    def speak():
        print "Rawr!";

class Lion():
    @staticmethod
    def speak():
        print "Roar!";

class Liger(Tiger, Lion):
    pass
'''both superclasses define a speak() method, and I need a way to detect this type of conflict.'''    

Liger.speak(); ''' this prints "Rawr" instead of printing an error message. '''
'''Is there any way to detect method name collisions like this one?'''
Run Code Online (Sandbox Code Playgroud)

可以在此处在线测试和调试代码:http : //ideone.com/xXOoVq

Fre*_*Foo 4

您可以使用元类检测此类冲突:

class ConflictCheck(type):
    def __new__(meta, name, bases, dct):
        # determine attributes per base class, except for magic ones
        attrs_per_base = [set(a for a in dir(b) if not a.startswith("__"))
                          for b in bases]
        if len(set.union(*attrs_per_base)) < sum(map(len, attrs_per_base)):
            raise ValueError("attribute conflict")
        return super(ConflictCheck, meta).__new__(meta, name, bases, dct)

class Liger(Lion, Tiger):
    __metaclass__ = ConflictCheck  # will raise an error at definition time
Run Code Online (Sandbox Code Playgroud)

Liger这是一个非常粗糙的第一个版本,错误消息很差,每当继承树中的上面的方法被重写时,实际上都会引发错误,但它应该足以让您开始。