我假设Python类中的私有静态方法是可以而且应该完成的。但实际上,我可能应该在类之外使用模块私有方法。
我想了解从不同的位置调用不同类型的静态方法:
我有一个Python类,它有一个私有的和一个公共的静态方法。我想从其他地方打电话给他们,从对方打电话给他们。
当在类之外调用公共静态方法时,我必须添加类名。i、 e
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的回答是否定的,那么结论是不能建立私有静态方法。
然后,我将在类之外创建一个私有模块方法,而不使用decorator。这相当于私有静态类方法。
def __my_privatemodulemethod(param1):
return param1
可以从我的模块中的任何地方调用它,不带前缀。
正如deceze在一个注释中已经提到的,在Python中,a
staticmethod
是一个不将实例或类作为第一个参数的方法。由于Python没有隐式的this
指针,显然staticmethod
无法引用当前类,因此它不能调用当前类上的另一个staticmethod
。这里最明显的解决方案是使用classmethods
(classmethods将当前类作为第一个参数):s/data migning/name mangling/g;)
“dunder”名称和名称管理机制不会使任何内容成为私有的:
As the "clunky" doc states,这里的重点主要是避免基类的一些重要实现部分被意外重写。实际上,这种方法很少使用,大多数时候甚至不需要。表示“implementation”方法和属性的约定是用单前导下划线命名它们。
顺便说一句,关于Python文档质量的尖刻评论不会给你的朋友带来太多帮助。
相关问题 更多 >
编程相关推荐