diff --git a/stock.py b/stock.py index bf69a82..920b9f7 100644 --- a/stock.py +++ b/stock.py @@ -2,8 +2,7 @@ from structure import Structure class Stock(Structure): - def __init__(self, name, shares, price): - self._init() + _fields = ('name', 'shares', 'price') @property def cost(self): @@ -12,5 +11,4 @@ class Stock(Structure): def sell(self, nshares): self.shares -= nshares - -Stock.set_fields() +Stock.create_init() diff --git a/structure.py b/structure.py index 5eae3ee..d6476c4 100644 --- a/structure.py +++ b/structure.py @@ -5,13 +5,6 @@ import sys class Structure: _fields = () - @staticmethod - def _init(): - locs = sys._getframe(1).f_locals - self = locs.pop('self') - for name, val in locs.items(): - setattr(self, name, val) - def __repr__(self): args = map(lambda field: f"{field}={getattr(self, field)!r}", self._fields) return f"{type(self).__name__}({', '.join(args)})" @@ -23,6 +16,10 @@ class Structure: raise AttributeError(f"No attribute {name}") @classmethod - def set_fields(cls): - sig = inspect.signature(cls) - cls._fields = tuple(sig.parameters) + def create_init(cls): + code = f'def __init__(self, {", ".join(cls._fields)}):\n' + for name in cls._fields: + code += f' self.{name} = {name}\n' + locs = {} + exec(code, locs) + cls.__init__ = locs['__init__']