我附上了几个类定义的代码列表。我的目标是创建一个带有事件处理程序的类,它可以在Timer过去时重复执行任务。在TimerClass中,我在类on_timed_event
中定义了一个方法__init__
。我在main函数a = TimerTest()
中实例化了一个TimerTest类,我发现它也执行了事件处理程序。
问题1.这是在创建对象实例时自动执行函数的方法吗?
问题2.我想将ClassA.method1传递给ClassB。我在main ()
传递sm.add()
延迟类正确的方式下面是这样做的吗?是否可以创建和延迟类的实例,并在一行中动态传递类实例SimpleMath(X,Y)和add()方法? Lambda函数?
import System
from System.Timers import (Timer, ElapsedEventArgs)
class TimerTest(object):
def __init__ (self):
self.timer = Timer()
self.timer.Interval= 1000
self.timer.Enabled = True
def on_timed_event (source, event):
print 'event from TimerTest class'
print "The Elapsed event was raised at " , event.SignalTime
print '------------'
self.timer.Elapsed += on_timed_event
class Delay(object):
def __init__(self,class_method):
self.delay = Timer()
self.delay.Interval= 2000
self.method= class_method
def on_timed_delay_event (self,sender, event):
print 'from Delay Class event handler'
print "event has elapsed event was raised at " , event.SignalTime
print 'addition results',self.method
print '------------'
def start(self):
print 'Delay timer Start'
self.delay.Elapsed += self.on_timed_delay_event
self.delay.Enabled= True
def stop(self):
self.delay.Enabled= False
self.delay.Elapsed -= self.on_timed_delay_event
class SimpleMath(object):
def __init__(self,a,b):
self.a =a
self.b =b
def add (self):
return self.a + self.b
def main():
a = TimerTest()
sm= SimpleMath(10,12)
print sm.add()
t= Delay(sm.add())
t.start()
if __name__ == '__main__':
main()
我正在为我的问题添加更多细节。类任务和请求被导入到包含MainForm类的模块中。在MainForm中我创建了一个Request类的实例,它被传递给Tab类,后者使用它并将其传递给Task类,该类应该在触发事件时执行任务。在下面的精简列表中,self.myRequest.command1仅执行一次。我在self.params内部执行后添加了一个打印,并打印None
。有什么特别的方式我应该通过self.myRequest.command1(arg1, arg2, arg3)
吗?
class Task(object):
...
def execute(self, param)
self.params = param #method to be executed periodically
print 'display self.params', self.params #debugging message
class Request (object):
...
def command1(self, arg1, arg2, arg3)
class Tab (object):
__init__(self,tabControl, myRequest):
self.myRequest= myRequest
self.myTask = Task()
...
def send_task(self):
self.myTask.execute(self.myRequest.command1(arg1, arg2, arg3))
class MainForm(Form):
__init__(self):
...
self.myRequest= Request()
self.tab=Tab(self.tabControl, self.myRequest)
...
答案 0 :(得分:1)
1
class A:
def some_func():
pass
def __init__(self):
self.init = 1
self.some_func() # just call member function
2.不,您不需要()
将函数作为参数传递
A类:
def some_func():
通
def func_of_func(func):
return fund()
def main():
a = A()
func_of_func(a.some_func) # no parentheses after some_func