Child function with additional conditions
Say I have the following:
class Parent(object):
[...]
def func(self, list):
for item in list:
if condition1:
do something
class Child开发者_开发问答(Parent):
[...]
def func(self, list):
for item in list:
if condition1 and condition2:
do something
What would be an elegant way to add condition2 to func without having to recopy the entire function? Note that I actually have two additional conditions in nested 'ifs'.
If you have access to Parent, you could do
class Parent(object):
[...]
def _condition(self, whatever):
return condition1
def func(self, list):
for item in list:
if self._condition(...):
do something
class Child(Parent):
[...]
def _condition(self, whatever):
return condition1 and condition2
Another way would be to evaluate the condition in an other method and override in the child:
class Parent(object):
[...]
def func(self, list):
for item in list:
if self.test(item):
do something
def test(self, item):
return condition1
class Child(Parent):
[...]
def test(self, item):
return super(Child, self).test(list) and condition2
Add a new method (function) that does the comparison (returns condition1 on Parent and condition1 and condition2 on Child). You would only have to modify that function in the child class.
Sorry buy I cannot write an example because I don't know Python :P
from functools import partial
class Parent(object):
[...]
def func(self, list, condition = lambda item: condition1):
for item in list:
if condition(item):
do something
class Child(Parent):
[...]
def func(self, list):
super(Child, self).func(list, condition = lambda item: condition1 and condition2)
if you only want to vary that one condition, or
class Parent(object):
[...]
def func(self, list):
for item in list:
self.whatever(item)
@staticmethod
def whatever(item):
if condition1:
do something
class Child(Parent):
[...]
@staticmethod
def whatever(item):
if condition1 and condition2:
do something
if you want to vary multiple things in the loop. do something
can also be another staticmethod
on Parent
if that is the same in both.
精彩评论