简体   繁体   English

如何更有效地触发class里面的function?

[英]How to trigger function inside class more effectively?

I am building a model with Python by using class method and there are serval functions inside the class.我正在使用 class 方法用 Python 构建一个 model,并且 class 中有一些函数。

The structure of my model is something like that:我的 model 的结构是这样的:

class testing ():
    def __init__ (self, number, lane, position):
        self.number = number
        self.lane = lane
        self.position = position
    def function_a (self):
        print('function_a')
    def function_b(self):
        print('function_b')
    def function_c(self):
        print('function_c')
    def function_d(self):
        print('function_d')

Function b needs to be triggered after function a has triggered.So, I write another function to solve this problem, where r1,r2 r3 are the name of each object under class.The structure of that function is like that: Function b需要在function a触发后触发。所以,我又写了一个function来解决这个问题,其中r1,r2 r3是class下的各个object的名字。那个88340040888的结构是这样的:6589

def A_then_B ():
    r1.function_a()
    r2.function_a()
    r3.function_a()
    r1.function_b()
    r2.function_b()
    r3.function_b()

It looks fine with only 3 objects, however, there are 24 objects under class method.它看起来只有 3 个对象,但在 class 方法下有 24 个对象。 And the function itself will become super long and not effective enough.而function本身会变得超长而且效果不够。 So, how can I modify my function so that it will not too long while doing the same work (all the objects trigger function a then trigger function b)?那么,我如何修改我的 function,使其在做同样的工作时不会太长(所有对象触发 function a 然后触发 function b)?

Put your objects in a collection and iterate through them:将您的对象放入集合中并遍历它们:

def A_then_B ():
   objects = (r1, r2)   # add as many as you have here
   for r in objects:
       r.function_a()
   for r in objects:
       r.function_b()

Better yet, pass the objects into your functions:更好的是,将对象传递给您的函数:

def A_then_B(objects):
   for r in objects:
       r.function_a()
   for r in objects:
       r.function_b()

def C_then_D(objects):
   for r in objects:
       r.function_c()
   for r in objects:
       r.function_d()

objects = (r1, r2)   # add as many as you have here
A_then_B(objects)
C_then_D(objects)

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

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