擅长:python、mysql、java
<p>为此,您可以使用<a href="https://docs.python.org/2/library/functions.html#getattr" rel="nofollow">^{<cd1>}</a>:</p>
<pre><code>class someClass(object):
def __init__(self,method=None):
methodList = ['methodOne','methodTwo']
if method in methodList:
self.chosenMethod = method
else:
self.chosenMethod = self.methodOne
def methodOne(self):
return 1
def methodTwo(self):
return 2
def calculate(self):
return getattr(self, self.chosenMethod)()
x = someClass(method='methodOne')
print x.calculate()
>>> 1
</code></pre>