如何从python中的其他方法调用私有静态方法

2024-05-14 18:50:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我假设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

可以从我的模块中的任何地方调用它,不带前缀。


Tags: 模块the方法returnmydefmyclassresult
1条回答
网友
1楼 · 发布于 2024-05-14 18:50:29

正如deceze在一个注释中已经提到的,在Python中,astaticmethod是一个不将实例或类作为第一个参数的方法。由于Python没有隐式的this指针,显然staticmethod无法引用当前类,因此它不能调用当前类上的另一个staticmethod。这里最明显的解决方案是使用classmethods(classmethods将当前类作为第一个参数):

class Foo(object):
    @classmethod
    def _protected(cls, arg):
        print("{}._protected() called with {}".format(cls.__name__, arg))

    @classmethod
    def public(cls, arg):
        cls._protected(arg)

there IS a notion of private/public achieved with data mingling

s/data migning/name mangling/g;)

“dunder”名称和名称管理机制不会使任何内容成为私有的:

class Foo(object):
    @staticmethod
    def __not_private():
        print("peek a boo")


Foo._Foo_not_private()

As the "clunky" doc states,这里的重点主要是避免基类的一些重要实现部分被意外重写。实际上,这种方法很少使用,大多数时候甚至不需要。表示“implementation”方法和属性的约定是用前导下划线命名它们。

顺便说一句,关于Python文档质量的尖刻评论不会给你的朋友带来太多帮助。

相关问题 更多 >

    热门问题