Вот небольшая модификация кода Ричарда, которая автоматически вызывает метод init_operations
при создании экземпляра Generator
.
class Generator:
def __init__(self, state):
self._state = state
if not hasattr(self, 'operations'):
self.init_operations()
@classmethod
def init_operations(cls):
cls.operations = {
PLUS: cls.plus,
MINUS: cls.minus,
}
def plus(self, a, b):
# Depends on state
return a + b
def minus(self, a, b):
return a - b if self._state else b - a
def generate(self):
a, b = give_me_numbers()
for op in self.operations:
print self.operations[op](self, a, b)
Вот альтернатива, которая делает operations
простой атрибут экземпляра. Это отнимает немного места, но это означает, что вам не нужно явно пропускать self
при вызове операции.
class Generator(object):
def __init__(self, state=False):
self._state = state
self.operations = {
PLUS: self.plus,
MINUS: self.minus
}
def plus(self, a, b):
# Depends on state
return a + b
def minus(self, a, b):
return a - b if self._state else b - a
def generate(self):
a, b = give_me_numbers()
for op in OPERATIONS:
print self.operations[op](a, b)
И, наконец, эта вариация использует имена методов для идентификации операций вместо целых чисел.
#!/usr/bin/env python
from random import seed, randint
def give_me_numbers():
a, b = randint(1, 99), randint(1, 99)
print 'a=%d, b=%d' % (a, b)
return a, b
OPERATIONS = ('plus', 'minus')
class Generator(object):
def __init__(self, state=False):
self._state = state
def plus(self, a, b):
# Depends on state
return a + b
def minus(self, a, b):
return a - b if self._state else b - a
def operations(self, op):
return getattr(self, op)
def generate(self):
a, b = give_me_numbers()
for op in OPERATIONS:
#print getattr(self, op)(a, b)
print self.operations(op)(a, b)
seed(42)
g1 = Generator(False)
g1.generate()
g2 = Generator(True)
g2.generate()
выход
a=64, b=3
67
-61
a=28, b=23
51
5
Вы не действительно нужен метод operations
здесь - я просто оставил его, чтобы остаться (относительно) в соответствии с кодом ОП. Вместо этого вы можете просто позвонить getattr(self, op)(a, b)
напрямую. OTOH, это is очиститель для подачи operations
метод, если вы хотите назвать его вне класса.
Кажется хорошим решением. Это эквивалентно ответу EOL? – Moberg
его эквивалентно моему :) – Richard