基于角色的发展
py-roles的Python项目详细描述
基于角色开发的库。
与MIXIN的最大区别是,这个角色只应用于主题实例,而不应用于主题类(唉,构建一个新的类)。
可以分配和撤消角色。一个实例可以应用多个角色。撤销可以按任何特定顺序发生。
使用角色 作为一个基本示例,考虑一个域类:
>>> class Person: ... def __init__(self, name): ... self.name = name >>> person = Person("John") The instance should participate in a collaboration in which it fulfills a particular role:
>>> from roles import RoleType >>> class Carpenter(metaclass=RoleType): ... def chop(self): ... return "chop, chop" Assign the role to the person:
>>> Carpenter(person) # doctest: +ELLIPSIS <Person+Carpenter object at 0x...> >>> person # doctest: +ELLIPSIS <Person+Carpenter object at 0x...> The person is still a Person:
>>> isinstance(person, Person) True … and can do carpenter things:
>>> person.chop() 'chop, chop' Context Roles make a lot of sense when used in a context. A classic example is the money transfer example. Here two accounts are used and an amount of money is transfered from one account to the other. So, one account playes the role of source account and the other plays the role of target account.