python 类装饰器与元类

类装饰器,元类

还有一些技术可以简化上面的代码,其中一种是使用类装饰器:

Class decorator to apply constraints

def check_attributes(**kwargs):
def decorate(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 decorate

Example

@check_attributes(name=SizedString(size=8),
shares=UnsignedInteger,
price=UnsignedFloat)
class Stock:
def init(self, name, shares, price):
self.name = name
self.shares = shares
self.price = price
另外一种方式是使用元类:

A metaclass that applies checking

class checkedmeta(type):
def new(cls, clsname, bases, methods):
# Attach attribute names to the descriptors
for key, value in methods.items():
if isinstance(value, Descriptor):
value.name = key
return type.new(cls, clsname, bases, methods)

Example

class Stock2(metaclass=checkedmeta):
name = SizedString(size=8)
shares = UnsignedInteger()
price = UnsignedFloat()

def __init__(self, name, shares, price):
    self.name = name
    self.shares = shares
    self.price = price

你可能感兴趣的:(python 类装饰器与元类)