Python 的私有和受保护访问修饰符
项目描述
Python 的访问修饰符
这个包为 Python 提供了两个访问修饰符:私有方法和受保护方法。目标是能够将方法记录为私有或受保护的,并提供基本的防护措施,防止从允许的范围之外意外调用私有和受保护的方法。
如何使用
私有方法的示例用法:
from access_modifiers import privatemethod
class Class:
@privatemethod
def private_method(self) -> str:
return "private method"
def public_method(self) -> str:
return "public method calls " + self.private_method()
c = Class()
print(c.public_method()) # Prints "public method calls private method"
print(c.private_method()) # Raises an exception
受保护方法的示例用法:
from access_modifiers import protectedmethod
class Class:
@protectedmethod
def protected_method(self) -> str:
return "protected method"
def public_method(self) -> str:
return "public method calls " + self.protected_method()
class Subclass(Class):
@protectedmethod
def protected_method(self) -> str:
return "overridden protected method calls " + super().protected_method()
c = Subclass()
print(c.public_method()) # Prints "public method calls overridden protected method calls protected method"
print(c.protected_method()) # Raises an exception
私有方法可以与静态方法结合使用。注意顺序很重要:staticmethod 应该是最外层的装饰器。
from access_modifiers import privatemethod
class Class:
@staticmethod
@privatemethod
def static_private_method() -> str:
return "static private method"
def public_method(self) -> str:
return "public method calls " + self.static_private_method()
c = Class()
print(c.public_method()) # Prints "public method calls static private method"
print(c.static_private_method()) # Raises an exception
不支持将受保护的方法与静态方法结合使用。(尚)不支持将访问修饰符与类方法结合使用。
表现
访问修饰符装饰器通过查看调用装饰器的代码来决定是否允许调用该方法。为此,装饰器使用 CPython 的实现细节,如 sys._getframe() 和代码对象的名称,如 lambda 和模块。这些检查在每个方法调用上完成。因此,存在相当大的性能影响。access_modifiers.disable()因此,建议在测试期间使用访问修饰符,并在生产中使用该方法将其关闭。请注意,您需要在评估任何访问修饰符装饰器之前调用此方法,即:
from access_modifiers import disable, privatemethod
disable() # This will disable the access checks
class Class:
@privatemethod
def private_method(self) -> str:
return "private_method"
disable() # Calling disable here will not work, Class.private_method has already been wrapped
安装
该包可从 Python 包索引获得,使用pip install access-modifiers.
发展
要克隆存储库:git clone git@github.com:fniessink/access-modifiers.git.
要安装开发依赖项:pip install -r requirements-dev.txt.
要运行单元测试并测量覆盖率(应始终为 100%)ci/unittest.sh:.
运行 Pylint(它应该得 10 分)和 Mypy(它不应该抱怨)ci/quality.sh:
该实现由(单元)测试驱动,并具有 100% 的单元测试语句和分支覆盖率。请查看测试以了解当前涵盖了哪些使用场景。
项目详情
下载文件
下载适用于您平台的文件。如果您不确定要选择哪个,请了解有关安装包的更多信息。