【发布时间】:2018-04-18 10:14:11
【问题描述】:
我假设 Python 类中的私有静态方法是可以而且应该做的事情。但也许实际上,我应该只是在类外使用模块私有方法。
我想了解从不同位置调用不同种类的静态方法:
我有一个带有私有和公共静态方法的 Python 类。我想从其他地方给他们打电话,从对方那里打电话。
在类外调用公共静态方法时,我必须添加类名。即
m = MyClass.the_staticmethod(100) # I must use the classname as a prefix
查看代码中的问题:
class Myclass():
@staticmethod
__my_privatestaticmethod(myparam):
return myparam
@staticmethod
def the_staticmethod(myparam):
# will the following work?
result = __my_staticmethod(1) # will this work?
# data-mingling set as private, so following line cannot work!
result = Myclass.__my_staticmethod(2) # this cannot work.
result = the_staticmethod(3) # will this work without the prefix
return result
def __my_privatemethod(self, param1):
# which of the following are valid?
return __my_staticmethod(11) # will this work?
# data-mingling set as private, so following line cannot work!
return Myclass.__my_staticmethod(12) # this cannot work.
return the_staticmethod(13) # will this work without the prefix of the class?
return self.the_staticmethod(14) # will this work. Is the self also considered the class?
return Myclass.the_staticmethod(15) # this of course works.
def the_method(param1):
return __my_staticmethod(param1) # will this work?
如果 1 和 11 的答案是否定的,那么结论是你不能创建私有静态方法。
然后我会在没有装饰器的类之外创建一个私有模块方法。这相当于私有静态类方法。
def __my_privatemodulemethod(param1):
return param1
并且可以从我的模块中的任何位置调用它,无需前缀。
【问题讨论】:
-
Python 没有私有与公共类元素。如果存在,可以引用。
-
Python 不是
C#。我想你想要达到的目标有更多pythonic等价物。 -
我不明白你的问题是什么。您可以通过尝试逐个运行它们来找出其中哪些调用有效;你需要我们做什么?
-
staticmethod是一种不接收cls或self参数的方法。如果您确实想访问同一类/实例的其他方法,那么该方法确实不应该是static。 -
是的,这就是为什么我明确使用了__private这个词,并在示例中使用了dunder来进行数据混合。
标签: python class methods static