我希望对象在其例程中调用某种方法(在变量中分配的特定方法)。我设法用字典来做到这一点,并且我还设法通过在对象创建后分配变量来做到这一点。哪种方式更好?还有其他更清洁的方法吗?
第一种有效方法(字典):
class Foo:
def __init__(self, name, funcin) -> None:
self.name = name
self.func = {
'bear': self.bear,
'boar': self.boar,
}[funcin]
def routine(self):
print('fluff')
self.func()
def bear(self):
print(f'I, {self.name}, am a bear and I like honey.')
def boar(self):
print(f'I, {self.name}, am a boar and I like fruits.')
bob = Foo('bob', 'bear')
mark = Foo('mark', 'boar')
bob.routine()
mark.routine()
Run Code Online (Sandbox Code Playgroud)
第二种有效的方法(另一行分配):
class Foo:
def __init__(self, name) -> None:
self.name = name
def routine(self):
print('fluff')
self.func()
def bear(self):
print(f'I, {self.name}, am a bear and …Run Code Online (Sandbox Code Playgroud)