有没有办法重新定义的行为。 python类的运算符?

时间:2014-10-30 20:43:58

标签: python operator-overloading override overloading

这是问题,我有一个类,我想在python中定义,以便能够将buck传递给另一个类,以便在调用主类的函数时说话。 例如:

class Multi_Interface:
    def __init__(self):
        interfaces = [Interface("message A"), Interface("Message B")]
        self.set_interface(0)

    def set_interface(self, interface_index = 0):
        current_interface = self.interfaces[interface_index]
    # @todo: override the .operator to call the member of the current interface.

class Interface:
    def __init__(self, message):
        self.msg = message

    def do_stuff(self, message="I am a parameter"):
        print message + self.msg

mi = Multi_Interface()
mi.do_stuff(message="the internal message is: ")
mi.set_interface(1)
mi.do_stuff(message="the internal message is: ")
mi.do_stuff()

>>> the internal message is: mesage A
>>> the internal message is: mesage B
>>> I am a parameter: mesage B

有没有办法为类重载此运算符? 怎么会超载这个运算符? 我知道如何从子对象获取方法,前提是我可以在方法中获取字符串。

1 个答案:

答案 0 :(得分:0)

最终解决方案如下

class Multi_Interface:
    def __init__(self):
        self.interfaces = [Interface("message A"), Interface("Message B")]
        self.current_interface = None
        self.set_interface(0)

    def set_interface(self, interface_index = 0):
        self.current_interface = self.interfaces[interface_index]

    def __getattr__(self, name):
        return getattr(self.current_interface, name)

class Interface:
    def __init__(self, message):
        self.msg = message

    def do_stuff(self, message="I am a parameter "):
        print message + self.msg

mi = Multi_Interface()
mi.do_stuff(message="the internal message is: ")
mi.set_interface(1)
mi.do_stuff(message="the internal message is: ")
mi.do_stuff()