Passing data to another class in Python

后端 未结 1 763
抹茶落季
抹茶落季 2021-01-16 21:17

I am using Twisted and have a couple of callbacks, both of different types (so they don\'t share a factory). I am trying to get data from one callback object to another:

相关标签:
1条回答
  • 2021-01-16 21:52

    I made some changes to the below code, essentially you need to remember:

    1. To use the self keyword when creating object methods.
    2. You need to either pass the data value as a method argument, or assign it somehow (see below).

    Here is an example of how to pass data class-to-class:

    class CallbackA(object):
        def transmit(self,data):  # See note 1
            do_stuff_with(data)   # See note 1
    
    class CallbackB(object):
        def doRead(self,data):              # see note 1
            self.point_to_A.transmit(data)  # see note 2
    
    class bigClass(object):
        def __init__(self):
            self.A = CallbackA()
            self.B = CallbackB()
            self.B.point_to_A = self.A
    

    the above code will probably not work verbatim but is an example of how you could pass data to another class in the way you describe. You should be able to get yours working from this example.

    And then when it is called:

    test = bigClass()
    test.B.doRead(data)
    

    Note 1: You need to declare the data somehow. Either pass it as a method argument as I have shown, or you need to declare it as a property:

    class CallbackA(object):
        def transmit(self,data):
            do_stuff_with(self.data)
    
    class CallbackB(object):
        def __init__(self,data):
            self.data = data
    
        def doRead(self):
            self.point_to_A.transmit(self.data)
    

    or

    class CallbackA(object):
        def transmit(self,data):
            do_stuff_with(self.data)
    
    class ClassB(object):
        def set_data(self,data):
            self.data = data
    
        def doRead(self):
            self.point_to_A.transmit(self.data)
    

    Note 2: You either need to call the method as: method(class_instance, args) or class_instance.method(args)

    EDIT

    As an add-on to our discussion in comments. Explicit declaration of point_to_A

     class ClassB(object):
        def __init__(self,A):
            self.point_to_A = A
    
        def set_data(self,data):
            self.data = data
    
        def doRead(self):
            self.point_to_A.transmit(self.data)
    
    0 讨论(0)
提交回复
热议问题