对自己使用 getattr()
Using getattr() on self
我有一个 class,在 class 的方法之一中,我有一个从用户输入中给出的字符串,然后映射到相应的方法(技术上是 str 的表示方法)。如何在尚未创建 class 实例的情况下调用此方法,即使用 self.争论。我已经包含了我认为可行但行不通的内容...
class RunTest():
def __init__(self, method_name):
self.method_name = method_name #i.e., method_name = 'Method 1'
def initialize_test(self):
mapping = {'Method 1': 'method1()', 'Method 2': 'method2()', ...}
test_to_run = getattr(self, mapping[self.method_name])
def method1(self):
....
def method2(self):
....
如果我理解正确的话,您想将 类 属性映射到基于用户输入的方法。这应该做你想做的事:
class YourClass:
def __init__(self, method_name):
mapping = {'Method 1': self.method_one,
'Method 2': self.method_two}
self.chosen_method = mapping[method_name]
def method_one(self):
print('method one')
def method_two(self):
print('method two')
while True:
name = input("enter 'Method 1' or 'Method 2'")
if name != 'Method 1' and name != 'Method 2':
print('Invalid entry')
else:
break
your_class = YourClass(name)
your_class.chosen_method()
这完全避免了使用 getattr()
。确保在您的映射字典中,方法没有括号(例如 {'Method 1': self.method_one()...
)。如果这样做,那么 chosen_method
将等于该方法 returns。
我有一个 class,在 class 的方法之一中,我有一个从用户输入中给出的字符串,然后映射到相应的方法(技术上是 str 的表示方法)。如何在尚未创建 class 实例的情况下调用此方法,即使用 self.争论。我已经包含了我认为可行但行不通的内容...
class RunTest():
def __init__(self, method_name):
self.method_name = method_name #i.e., method_name = 'Method 1'
def initialize_test(self):
mapping = {'Method 1': 'method1()', 'Method 2': 'method2()', ...}
test_to_run = getattr(self, mapping[self.method_name])
def method1(self):
....
def method2(self):
....
如果我理解正确的话,您想将 类 属性映射到基于用户输入的方法。这应该做你想做的事:
class YourClass:
def __init__(self, method_name):
mapping = {'Method 1': self.method_one,
'Method 2': self.method_two}
self.chosen_method = mapping[method_name]
def method_one(self):
print('method one')
def method_two(self):
print('method two')
while True:
name = input("enter 'Method 1' or 'Method 2'")
if name != 'Method 1' and name != 'Method 2':
print('Invalid entry')
else:
break
your_class = YourClass(name)
your_class.chosen_method()
这完全避免了使用 getattr()
。确保在您的映射字典中,方法没有括号(例如 {'Method 1': self.method_one()...
)。如果这样做,那么 chosen_method
将等于该方法 returns。