有没有办法让继承的方法执行检查,如果检查失败则返回原始方法? (Python)
Is there a way to have an inherited method perform a check, then refer back to the original method if the check fails? (Python)
假设我有一个父 class 和一个子 class,看起来像这样:
class Parent():
def __init__(self,value):
self.value = self.value
def get_value(self):
return self.value
class Child(Parent):
def __init__(self,value):
super(Child,self).__init__(value)
def get_value(self):
if self.value == 10
print("Yay!")
else:
Parent.get_value()
所以像上面一样,我想要一个父 class 的子 class 覆盖从父 class 继承的方法,但我希望它检查一个特定的条件。如果不满足该特定条件(在本例中 self.value = 10),则只需 运行 来自父 class.
的方法
编辑:修复语法错误
你可以这样做
class Parent:
def __init__(self, value):
self.value = value
def get_value(self):
print(f'parrent {self.value}')
return self.value
class Child(Parent):
def __init__(self,value):
super(Child,self).__init__(value)
def get_value(self):
if self.value == 10:
print(f'child {self.value}')
print("Yay!")
else:
super().get_value()
c = Child(10)
c.get_value()
cp = Child(11)
cp.get_value()
输出
child 10
Yay!
parrent 11
假设我有一个父 class 和一个子 class,看起来像这样:
class Parent():
def __init__(self,value):
self.value = self.value
def get_value(self):
return self.value
class Child(Parent):
def __init__(self,value):
super(Child,self).__init__(value)
def get_value(self):
if self.value == 10
print("Yay!")
else:
Parent.get_value()
所以像上面一样,我想要一个父 class 的子 class 覆盖从父 class 继承的方法,但我希望它检查一个特定的条件。如果不满足该特定条件(在本例中 self.value = 10),则只需 运行 来自父 class.
的方法编辑:修复语法错误
你可以这样做
class Parent:
def __init__(self, value):
self.value = value
def get_value(self):
print(f'parrent {self.value}')
return self.value
class Child(Parent):
def __init__(self,value):
super(Child,self).__init__(value)
def get_value(self):
if self.value == 10:
print(f'child {self.value}')
print("Yay!")
else:
super().get_value()
c = Child(10)
c.get_value()
cp = Child(11)
cp.get_value()
输出
child 10
Yay!
parrent 11