1

いくつかのメソッドを含むクラス Population があります。

Population入力によると、クラスのインスタンスでメソッドを特定の順序で実行したいと考えています。

私が達成しようとしていることをもう少し正確にすることは、使用することとまったく同じです:

stuff = input(" enter stuff ")

dico = {'stuff1':functionA, 'stuff2':functionC, 'stuff3':functionB, 'stuff4':functionD}

dico[stuff]()

functionA、functionB などは関数ではなくメソッドであることを除いて:

order_type = 'a'
class Population (object):
    def __init__(self,a):
        self.a = a

    def method1 (self):
        self.a = self.a*2
        return self

    def method2 (self):
        self.a += 2
        return self

    def method3 (self,b):
        self.a = self.a + b
        return self

if order_type=='a':
    order = {1:method1, 2:method2, 3:method3}
elif order_type=='b':
    order = {1:method2, 2:method1, 3:method3}
else :
    order = {1:method3, 2:method2, 3:method1}

my_pop = Population(3)

while iteration < 100:
    iteration +=1
    for i in range(len(order)):
        method_to_use = order[i]
        my_pop.method_to_use() # But obviously it doesn't work!

私の質問が十分に明確になったことを願っています!私のメソッドの1つは2つの引数を必要とすることに注意してください

4

3 に答える 3

2

使用getattr:

order = {1:'method1', 2:'method2', 3:'method3'} #values are strings
...
method_to_use = order[i]
getattr(mypop, method_to_use)()
于 2013-08-04T11:33:06.023 に答える
2

インスタンスを最初の引数として明示的に渡します。

method_to_use = order[i]
method_to_use(my_pop)

完全な作業コード:

order_type = 'a'
class Population (object):
    def __init__(self,a):
        self.a = a

    def method1 (self):
        self.a = self.a*2
        return self

    def method2 (self):
        self.a += 2
        return self

    def method3 (self):
        self.a = 0
        return self

if order_type=='a':
    order = [Population.method1, Population.method2, Population.method3]
elif order_type=='b':
    order = [Population.method2, Population.method1, Population.method3]
else :
    order = [Population.method3, Population.method2, Population.method1]

my_pop = Population(3)

while iteration < 100:
    iteration +=1
    for method_to_use in order:
        method_to_use(my_pop)

複数の引数を渡したい場合は、次の*args構文を使用します。

if order_type=='a':
    order = [Population.method1, Population.method2, Population.method3]
    arguments = [(), (), (the_argument,)]
elif order_type=='b':
    order = [Population.method2, Population.method1, Population.method3]
    arguments = [(), (), (the_argument,)]
else :
    order = [Population.method3, Population.method2, Population.method1]
    arguments = [(the_argument, ), (), ()]

my_pop = Population(3)

while iteration < 100:
    iteration +=1
    for method_to_use, args in zip(order, arguments):
        method_to_use(my_pop, *args)

()空のタプルであるため*args、追加の引数なしに展開されます(the_argument,)が、 は引数をメソッドに渡す 1 要素のタプルです。

于 2013-08-04T11:33:38.497 に答える
2

使用できますoperator.methodcaller

from operator import methodcaller
method_to_use = methodcaller('method' + str(i))
method_to_use(my_pop)
于 2013-08-04T11:38:07.313 に答える