简体   繁体   English

有没有一种方法可以重新定义的行为。 python类的运算符?

[英]is there a way to redefine the behavior for the . operator for a python class?

Here is the problem, I have a class that I would like to define in python to be able to pass the buck onto another class so to speak when a function to the primary class is called. 这是问题所在,我有一个要在python中定义的类,以便能够将buck传递给另一个类,这样可以说在调用主类的函数时。 For example: 例如:

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

Is there a way to overload this operator for a class? 有没有办法重载该运算符的类? How would one overload this operator? 一个运算符将如何重载? I have an idea on how to get the method from the child object provided I can get a string in a method. 我有一个关于如何从子对象获取方法的想法,只要可以在方法中获取字符串即可。

final solution is as follows 最终解决方法如下

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM