这是我的代码,我的目的是在初始化对象时将方法名称作为参数传递,并且我想运行方法'num'(第二个参数)次。基本上得到n个结果(如第二个参数中所述)。
class Foo(object):
faker = Faker()
def __init__(self, custom_method, num=1):
self.values = []
self.custom_method = custom_method
self.num = num
for x in self.num:
self.custom_method = self.values.append(custom_method)
def random_first_name(self):
self.custom_method = self.faker.first.name()
return self.custom_method
def random_phone(self):
self.custom_method = self.faker.random.phone()
return self.custom_method
b = Foo(random_first_name, 1)
c = Foo(random_phone,2)
答案 0 :(得分:2)
我想你可能想要使用函数getattr
。
class Foo(object):
faker = Faker()
def __init__(self, custom_method, num=1):
self.custom_method = custom_method
self.num = num
@property # Briefly, the property decorator makes the job of calling the callable for you. I.e. There is no need to do self.method(), self.method is enough.
def random_first_name(self):
return self.faker.first.name()
@property
def random_phone(self):
return self.faker.random.phone()
def call_method_num_times(self):
return [getattr(self, self.custom_method)\
for _ in range(self.num)]
我无法实例化此类,但可以按如下方式使用:
>>> foo1 = Foo('random_first_name', 1)
>>> foo1.call_method_num_times()
['John']
>>> foo2 = Foo('random_phone', 2)
>>> foo2.call_method_num_times()
['0123456789', '9876543210']
<小时/> 为(甚至更多)以(主观)更好的方式重组你的课程,我会做
class Foo(object):
def __init__(self):
self.faker = Faker()
@property
def random_first_name(self):
return self.faker.first.name()
@property
def random_phone(self):
return self.faker.random.phone()
def call_method_num_times(self, custom_method, num=1):
return [getattr(self, custom_method)\
for _ in range(num)]
因此允许您仅实例化Foo
一次
>>> foo = Foo()
>>> foo.call_method_num_times('random_first_name')
['John']
>>> foo.call_method_num_times('random_phone', 2)
['0123456789', '9876543210']
<小时/> 如果您对使用python native
property
描述符感到不舒服,可以将两种方法保持为明确的方法。在这种情况下,您可以按如下定义类
Foo
class Foo(object):
def __init__(self):
self.faker = Faker()
def random_first_name(self):
return self.faker.first.name()
def random_phone(self):
return self.faker.random.phone()
def call_method_num_times(self, custom_method, num=1):
return [getattr(self, custom_method)()\
for _ in range(num)]
使用Foo
>>> foo = Foo()
>>> foo.call_method_num_times('random_first_name')
['John']
>>> foo.call_method_num_times('random_phone', 2)
['0123456789', '9876543210']