创建仅在类内部使用的函数的最佳OOP方法是什么?



我想创建一个函数,它只用作同一类中另一个函数内部的函数。我的主要问题是,创建这个函数的最佳OOP方法是什么?我应该使用任何类型的装饰器吗?@statimethod等

对于info,它永远不会在类外部使用,它不需要在内部使用任何类变量(所以如果我们想使用@staticmethod,可能不需要self)

class Awesomeness(object):
def method(self, *args):
self._another_method(...)
pass
def _another_method(self, *args):
pass

我看到了两个合理的解决方案,每个都有自己的起伏:第一个静态私有方法:

class Awesomeness(object):
def method(self, *args):
self.__another_method(...)
pass
@staticmethod
def __another_method(*args):
pass

前导双下划线会导致名称混淆,因此在类之外必须使用_Awesomeness__another_method访问该方法。你也可以使用单个下划线来表示它应该是私有的,而不强制任何东西。

另一种解决方案,只有当你的一个类方法要使用这个函数时才有效,就是使它成为这个方法的内部类:

class Awesomeness(object):
def method(self, *args):
def another_method(*args):
pass
another_method(...)
pass

约定是使用单下划线和双下划线作为函数名的前缀。

例如

class Foo:
def _protected_function():
...

def __private_function():
...

这个答案进一步解释了它。

最新更新