我喜欢重写超类的方法之一,并对目标方法有不同的选项。例如,超类中的函数称为
__func__
,我有两个实现 __func1
和 __func2
实现 __func__
。我想根据用户的输入选择这两个函数在构造函数中之一。我尝试了一些我能想到的方法,但没有一个起作用。这是可能吗?如果是,正确的做法是什么?
编辑:我的类使用
__slots__
来定义成员变量,所以我不能使用类似 self.__func__ = self.__func1
的东西
是的,这是可能的。这是子类中的代码示例。父类中无需更改:
def __init__(self, user_input):
if (condition 1):
self.__func__ = self.func1
else:
self.__func__ = self.func2
def __func1(self, your arguments):
code
def __func2(self, your arguments)
other code
由于我不知道函数的参数或条件,所以这是我能得到的最具体的信息。
我认为您需要将
__init__
的用户输入存储到实例属性中:
class Parent(object):
def func(self):
raise NotImplementedError
class Child(Parent):
def __init__(self, user_input):
self.user_input = user_input
def func(self):
if self.user_input == "func1":
self._func1()
elif self.user_input == "func2":
self._func2()
else:
# make sure to guard against other possible inputs!
def _func1(self):
# implementation here
def _func2(self):
# implementation here
编辑:这是一个不存储用户输入的简单变体。也许还有其他更复杂的方法可以做到这一点。但这是最简单的之一:
class Parent(object):
def func(self):
raise NotImplementedError
class Child(Parent):
def __init__(self, user_input):
if user_input == "func1":
self.func = self._func1
elif user_input == "func2":
self.func = self._func2
else:
pass
# make sure to guard against other possible inputs!
def _func1(self):
print("from func1!")
def _func2(self):
print("from func12")
class Subclass(Superclass):
def __init__(self, choice=True, *args, **kwargs)
super().__init__(*args, **kwargs)
self.choice=choice
def __func__(self):
if self.choice:
return self.__func1()
else:
return self.__func2()
def __func1(self):
do something
def __func2(self):
do something