ex 6.5
This commit is contained in:
parent
da13371df1
commit
cf6de58a63
51
validate.py
51
validate.py
@ -1,3 +1,6 @@
|
|||||||
|
import inspect
|
||||||
|
|
||||||
|
|
||||||
class Validator:
|
class Validator:
|
||||||
def __init__(self, name=None):
|
def __init__(self, name=None):
|
||||||
self.name = name
|
self.name = name
|
||||||
@ -63,37 +66,23 @@ class NonEmptyString(String, NonEmpty):
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
class Stock:
|
class ValidatedFunction:
|
||||||
name = String()
|
def __init__(self, func):
|
||||||
shares = PositiveInteger()
|
self.func = func
|
||||||
price = PositiveFloat()
|
|
||||||
|
|
||||||
def __init__(self, name, shares, price):
|
def __call__(self, *args, **kwargs):
|
||||||
self.name = name
|
bound = inspect.signature(self.func).bind(*args, **kwargs)
|
||||||
self.shares = shares
|
if hasattr(self.func, '__annotations__'):
|
||||||
self.price = price
|
for arg in bound.arguments:
|
||||||
|
if arg in self.func.__annotations__ and issubclass(
|
||||||
|
self.func.__annotations__[arg], Validator
|
||||||
|
):
|
||||||
|
self.func.__annotations__[arg].check(bound.arguments[arg])
|
||||||
|
result = self.func(*args, **kwargs)
|
||||||
|
return result
|
||||||
|
|
||||||
def __repr__(self):
|
|
||||||
return f"Stock({self.name!r}, {self.shares!r}, {self.price!r})"
|
|
||||||
|
|
||||||
def __eq__(self, other):
|
if __name__ == '__main__':
|
||||||
if not isinstance(other, Stock):
|
def add(x: Integer, y: Integer):
|
||||||
return False
|
return x + y
|
||||||
return (self.name, self.shares, self.price) == (
|
add = ValidatedFunction(add)
|
||||||
other.name,
|
|
||||||
other.shares,
|
|
||||||
other.price,
|
|
||||||
)
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def from_row(cls, row):
|
|
||||||
return cls(*row)
|
|
||||||
|
|
||||||
@property
|
|
||||||
def cost(self):
|
|
||||||
return self.shares * self.price
|
|
||||||
|
|
||||||
def sell(self, num):
|
|
||||||
self.shares -= num
|
|
||||||
if self.shares < 0:
|
|
||||||
self.shares = 0
|
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user