根据类initiatiation参数确定要调用的类方法

时间:2015-11-03 08:16:32

标签: python class-method

我努力创建一个描述性标题,但我的挑战如下:

在我的Python应用程序中,我有一个通信模块,以前只使用过一种传输类型,串行。现在我还希望它包含另一个称为RTT的传输层。 我的班级COM包含connectsendreadlog等方法。现在我需要所有这些方法的两个不同版本,我想要它使被调用的方法在类实例化时决定。

E.g comlink = COM('RTT')将使用特定于RTT协议的send,read,connect集合,反之亦然,无需创建额外的类并决定在更高级别使用哪个类。

这可能吗?

2 个答案:

答案 0 :(得分:2)

Option Explicit Private Const PREFIX As String = "Module1.M" ' <-- Change this to match your Module Name and Prefix of the Sub Names Sub LoopCheckboxes() Dim sRun As String, oChkBox As Object For Each oChkBox In ActiveSheet.CheckBoxes With oChkBox Debug.Print "Checkbox name: " & .Name If .Value = 1 Then sRun = PREFIX & Mid(.Name, 3) Debug.Print "sRun: " & sRun Application.Run sRun End If End With Next End Sub Sub M1() Debug.Print "M1()" End Sub Sub M2() Debug.Print "M2()" End Sub Sub M3() Debug.Print "M3()" End Sub 成为返回正确类实例的函数。 E.g。

COM()

您也可以将此作为基类的类方法。

def COM(ctype):
    try:
        klass = {
            'RTT' : ComRTT,
            'serial' : ComSerial}[ctype]
    except KeyError:
        raise ValueError("Invalid connection class: {}".format(ctype))
    instance = klass()
    return instance

>>> com = COM('RTT')

结果和模式是相同的,但后者可能更可取,因为它(可以说)更清楚地表明它与class Communication: @classmethod def from_type(cls, ctype): try: klass = { 'RTT' : ComRTT, 'serial' : ComSerial}[ctype] except KeyError: raise ValueError("Invalid connection class: {}".format(ctype)) return klass() >>> com = Communication.from_type('RTT') 类有关。

答案 1 :(得分:1)

鉴于我完全支持@HannesOvrén的评论和回答,这是另一种方法

class A():
    def __init__(self, protocol='SERIAL'):
        std_f = ('connect', 'send', 'read', 'log')
        protocols = ('RTT', 'SERIAL')
        if protocol not in protocols:
            print("Protocol not supported!")
            raise Exception # your exception here

        prot_f = [getattr(self, name+'_'+protocol.lower()) for name in std_f]
        for f, new_f in zip(std_f, prot_f):
            setattr(self, f, new_f)

    def connect_serial(self, hostname):
        print('I am serial connect', hostname)
    def send_serial(self, hostname):
        print('I am serial send', hostname)
    def read_serial(self, hostname):
        print('I am serial read', hostname)
    def log_serial(self, hostname):
        print('I am serial log', hostname)

    def connect_rtt(self, hostname):
        print('I am RTT connect', hostname)
    def send_rtt(self, hostname):
        print('I am RTT send', hostname)
    def read_rtt(self, hostname):
        print('I am RTT read', hostname)
    def log_rtt(self, hostname):
        print('I am RTT log', hostname)

基本上,根据给定的协议,在实例化类时,它会分配标准函数的名称

>>> from two_types_of_methods import A
>>> a=A('RTT')
>>> a.connect('myserv.com')
I am RTT connect myserv.com
>>> a.send('myserv.com')
I am RTT send myserv.com
>>> a.read('myserv.com')
I am RTT read myserv.com
>>> a.log('myserv.com')
I am RTT log myserv.com
>>> b=A()
>>> b.connect('myserv.com')
I am serial connect myserv.com
>>> b.send('myserv.com')
I am serial send myserv.com
>>> b.read('myserv.com')
I am serial read myserv.com
>>> b.log('myserv.com')
I am serial log myserv.com