Python3 class refactor
I wrote some python3 code a long time ago and it’s very ugly. It has a lot of boilerplate and definitely can be improved. I need advice on how to make it better. please take a look
def _safe_value(value, default, reject=None):
return value if value is not reject else default
# Bullet class
class Bullet(GameParticle):
def __init__(self, x, y, angle, speed=None, rad=None, weapon=None,
color=None, hp=1.0, dmg=1.0, lifespan=60 * 4):
if isinstance(weapon, WeaponType):
speed = _safe_value(speed, weapon.speed)
rad = _safe_value(rad, weapon.rad)
hp = _safe_value(hp, weapon.hp, 1.0)
dmg = _safe_value(dmg, weapon.dmg, 1.0)
color = _safe_value(color, weapon.color)
speed = _safe_value(speed, 0.0)
rad = _safe_value(rad, BULLET_RADIUS)
color = _safe_value(color, BULLET_COLOR)
super().__init__(x, y, angle, speed, rad, color, hp, dmg)
self.lifespan = lifespan
Details
- None is used to indicate unspecified value.
- I did not register a float value as “unspecified” because it may be
used. - I dont want to change the function params because it’s already in
use.
Difficulties
- when
__init__
is called, sometimes it’s with aWeaponType
, sometimes it’s not - when
WeaponType
is specified, other params such asspeed
may still be specified and we need to follow the specifiedspeed
instead - I tried to create a general function that filters the values but then ill need to use
getattr(weapon, varname)
which is even worse
Goal
- call
_safe_value
only once for each argument - if possible remove the mumbo jumbo from the
__init__