ex 6.4
This commit is contained in:
parent
18fb6da5ad
commit
da13371df1
6
stock.py
6
stock.py
@ -2,8 +2,7 @@ from structure import Structure
|
|||||||
|
|
||||||
|
|
||||||
class Stock(Structure):
|
class Stock(Structure):
|
||||||
def __init__(self, name, shares, price):
|
_fields = ('name', 'shares', 'price')
|
||||||
self._init()
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def cost(self):
|
def cost(self):
|
||||||
@ -12,5 +11,4 @@ class Stock(Structure):
|
|||||||
def sell(self, nshares):
|
def sell(self, nshares):
|
||||||
self.shares -= nshares
|
self.shares -= nshares
|
||||||
|
|
||||||
|
Stock.create_init()
|
||||||
Stock.set_fields()
|
|
||||||
|
|||||||
17
structure.py
17
structure.py
@ -5,13 +5,6 @@ import sys
|
|||||||
class Structure:
|
class Structure:
|
||||||
_fields = ()
|
_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):
|
def __repr__(self):
|
||||||
args = map(lambda field: f"{field}={getattr(self, field)!r}", self._fields)
|
args = map(lambda field: f"{field}={getattr(self, field)!r}", self._fields)
|
||||||
return f"{type(self).__name__}({', '.join(args)})"
|
return f"{type(self).__name__}({', '.join(args)})"
|
||||||
@ -23,6 +16,10 @@ class Structure:
|
|||||||
raise AttributeError(f"No attribute {name}")
|
raise AttributeError(f"No attribute {name}")
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def set_fields(cls):
|
def create_init(cls):
|
||||||
sig = inspect.signature(cls)
|
code = f'def __init__(self, {", ".join(cls._fields)}):\n'
|
||||||
cls._fields = tuple(sig.parameters)
|
for name in cls._fields:
|
||||||
|
code += f' self.{name} = {name}\n'
|
||||||
|
locs = {}
|
||||||
|
exec(code, locs)
|
||||||
|
cls.__init__ = locs['__init__']
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user