I have a scheme like:
class Base(object):
param, d=0, 1
def get_all(self):
while True:
a = self.get_xxx(param)
if not a:
break
handle(a)
param += d
class A(Base):
def get_xxx(param):
return some_method(param)
class B(Base):
def get_xxx(param):
return other_method(param)
Then, I was informed that for B, after each get_xxx param should be a+1 instead of param+d. That means I need to extract the param change logic at the end of get_all. I came up with a scheme using iterator:
class Base(object):
def get_all(self):
get_xxx = self.get_xxx()
while True:
a = get_xxx.next()
if not a:
break
handle(a)
class A(Base):
def get_xxx():
param, d = 0, 1
while True:
yield somemethod(param)
param += d
class B(Base):
def get_xxx():
param = 0
while True:
a = somemethod(param)
param = a + 1
yield a
Problem solved, but somehow I feel uncomfortable. So I wonder if there's a better solution? Many thanks!
I would make things like param
and d
instance attributes:
class Base(object):
def __init__(self):
self.param = 0
self.d = 1
then you don't have to pass anything explicitly into get_xxx()
. You could replace
param += d
with
self.iterate_param(a):
in Base.get_all()
then define iterate_param()
appropriately in your two subclasses, i.e.
class A(Base):
...
def iterate_param(self, a):
self.param += self.d
class B(Base):
...
def iterate_param(self, a):
self.param = a + 1
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments