我有三个案例:案例1,案例2,案例3:
我必须根据具体情况定义三个类。除了根据情况进行一些预处理之外,所有类都具有几乎相同的方法。如何在不一遍又一遍地重复相同代码的情况下做到这一点?
match condition:
case: "Case1"
class class1:
def method(self):
do something to self
return self
case: "Case2"
class Class2:
def method(self):
preprocessing1 on self
do exact something as in case 1
return self
case: "Case3"
class Class2:
def method(self):
preprocessing2 on self
do exact something as in case 1
return self
如何在不一遍又一遍地重复所有代码的情况下实现这一目标?
我会使用继承,唯一的缺点是在所有情况下都定义了class1
注意:当您已经引用它时,我看不到返回 self 的优点
伪代码映射到您的示例中
class class1:
def method(self):
do something to self
case "Case2":
class Class2(Class1):
def method(self):
preprocessing1 on self
super().method() # do exact something as in case 1
case "Case3":
class Class2(Class1):
def method(self):
preprocessing2 on self
super().method() # do exact something as in case 1