1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| class Stock: name = SizedString("name", size=8) shares = UnsignedInteger("shares") price = UnsignedFloat("price")
def __init__(self, name, shares, price): self.name = name self.shares = shares self.price = price
def check_attributes(**kwargs): def decrator(cls): for key, value in kwargs.items(): if isinstance(value, Descriptor): value.name = key setattr(cls, key, value) else: setattr(cls, key, value(key)) return cls return decrator
@check_attributes(name=SizedString(size=8), shares=UnsignedInteger, price=UnsignedFloat) class Stock2: def __init__(self, name, shares, price): self.name = name self.shares = shares self.price = price
class checkmeta(type): def __new__(cls, clsname, bases, methods): for key, value in method.items(): if isinstance(value, Descriptor): value.name = key return type.__new__(cls, clsname, bases, methods)
class Stock3(metaclass=checkdmeta): name = SizedString(size=8) shares = UnsignedInteger() price = UnsignedFloat()
def __init__(self, name, shares, price): self.name = name self.shares = shares self.price = price
|