@python的重写和@final实现
strictparent的Python项目详细描述
严格父级
python被构建成尽可能动态和允许的。然而,特别是在更大的应用中,建立更严格的原则是有益的。strictparent可以帮助您使python类更加结构化并强制执行契约,同时在必要时仍有机会打破规则。
重量轻,无依赖性
安装
pip install strictparent
需要Python3.6+。
功能
StrictParent
——使用这些功能的所有自定义类的父类@final
——使方法定稿,如果子类试图重写此方法,则引发InheritanceError
。@overrides
——方法的decorator声明此子类方法正在重写父类中的方法。如果父类没有这样的方法,则引发一个InheritanceError
。此外,如果子类重写父类方法而不使用此装饰器使其显式,则会引发异常。@force_override
——用于重写最终确定的父类方法的修饰符。
所有的decorator也可以用于内联类。
这种方法的目的是使代码更易于理解,并保护开发人员不被意外重写方法,该方法在父类中起着重要作用。但是,如果由@force_override
decorator显式声明,则仍然可以重写所有方法。这样我们就可以在不失去任何自由的情况下编写更可读的代码。
StrictParent
没有元类,因此您不必面对有关元类冲突的任何问题。
fromstrictparentimportStrictParent,final,overridesclassParent(StrictParent):defoverrideable_method(self):return'I do not mind being overridden'@finaldeffinal_method(self):return'Knowledge & vision arose in me: this is the last birth. There is now no further becoming.'classObedientChild(Parent):@overrides# It is now easy to see, that the method has a meaning in the `Parent` classdefoverrideable_method(self):return'Hey'@force_override# Finalized methods can be overridden if explicitly stateddeffinal_method(self):return'I am aware I have broken the convention'classRebelChild(Parent):@overrides# Will raise an exception, because `Parent` class has no such methoddefmy_heretic_method(self):return'I claim to be be authentic, but I am just a faker'# Will raise an exception, because `@overrides` decorator is missingdefoverrideable_method(self):return'I am hiding my lineage'# Will raise an exception, because `final_method` has been finalized in `Parent` classdeffinal_method(self):return'I am against the machine!'
与内置装饰器一起使用
您可以将自定义装饰器与内置的@classmethod
、@staticmethod
和@property
装饰器组合在一起。自定义装饰器必须是最终包装器,因此将其添加到所有其他装饰器的顶部:
@final@overrides@classmethoddefoverrideable_method(self):pass
请让我们知道,如果有任何其他功能,应该添加到这个包。
贡献
不需要虚拟环境,因为您不需要安装任何依赖项。
运行测试
在根目录中:
cd strictparent/
./tests.py