所以我有一个类有几个(普通)方法。 取决于我想要调用不同方法的值。 选择方法的这种行为是静态的(对于类的所有实例化都是一样的。你会如何推荐这样做?
如果实例化的状态是常量并且在初始化后永远不会改变,那么答案是否会以最佳方式实现?
例:
PLUS = 0 MINUS = 1 OPERATIONS = [PLUS, MINUS] class Generator(object): operations = { PLUS: self.plus, # Not possible MINUS: self.minus, } def __init__(self, state): 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 generate(self): a, b = give_me_numbers() for op in OPERATIONS: print self.operations[op](a, b)So I have a class with a couple of (normal) methods. Depending on a value I want to call different methods. This behavior of choosing methods is static (same for all instantiation of the classes. How would you recommend doing this?
Will the answer change on best way to achieve this if the state of an instantiation is constant and never changes after initialization?
Example:
PLUS = 0 MINUS = 1 OPERATIONS = [PLUS, MINUS] class Generator(object): operations = { PLUS: self.plus, # Not possible MINUS: self.minus, } def __init__(self, state): 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 generate(self): a, b = give_me_numbers() for op in OPERATIONS: print self.operations[op](a, b)最满意答案
PLUS = 0 MINUS = 1 OPERATIONS = [PLUS, MINUS] class Generator: operations = {} def __init__(self, state): self._state = state @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 = 5, 10 for op in self.operations: print( self.operations[op](self, a, b) ) gen = Generator(1) gen.init_operations() gen.generate()为了使operations存储类定义的函数,它不能像你所做的那样在类的顶部完成。 这是因为解析器找不到你所引用的函数,因为它还没有解析它们。 所以我添加了一个'静态'init_operations()。
注意这些操作存储为未绑定的方法(因为它是从静态内部调用的); 因此,在调用这些函数时,必须包含self变量作为第一个参数。
PLUS = 0 MINUS = 1 OPERATIONS = [PLUS, MINUS] class Generator: operations = {} def __init__(self, state): self._state = state @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 = 5, 10 for op in self.operations: print( self.operations[op](self, a, b) ) gen = Generator(1) gen.init_operations() gen.generate()In order for operations to store functions of a class definition it can't be done at the top of a class like you have done. This is because the parser won't find the functions you're referring to because it hasn't parsed them yet. So instead I've added a 'static' init_operations().
Note these operations are stored as unbound methods (since it's called from within a static); therefore when calling these functions it is necessary to include the self variable as the 1st argument.
更多推荐
发布评论