擅长: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):
# store it with the object so we can access it later in calculate method
self.method = method
def methodOne(self):
return 1
def methodTwo(self):
return 2
def calculate(self):
# get the actual method from the string here
# if no such method exists then use methodOne instead
return getattr(self, self.method, self.methodOne)()
> someClass('methodOne').calculate()
# 1
> someClass('methodTwo').calculate()
# 2
</code></pre>