简体   繁体   English

从另一个模块在python中调用私有类成员函数

[英]Calling a private class member function in python from another module

Is it possible to call private functions declared in another class ? 是否可以调用在另一个类中声明的私有函数? If yes, I need to call a function inside my main file. 如果是,我需要在主文件中调用一个函数。 This function has to be imported from another module. 此功能必须从另一个模块导入。 This function is defined inside a class as follows. 该函数在类内定义如下。

class ConfLoader(object):
.....
    def _set_config_value(self, section, attribute, value):
....

Any suggestions ? 有什么建议么 ?

Python does not have "enforced" private functions, but it does have a naming convention that makes it harder to do accidentally . Python没有“强制”私有功能,但是它确实有一个命名约定,这使得它更难于意外执行 This is usually done by prepending a double underscore (not, as in your example, a single one, which functions as a normal method name). 这通常是通过在下划线前加一个下划线来实现的(而不是像您的示例中那样,一个下划线作为常规方法名称)。 For example: 例如:

class X(object):
    def __f(self):
        print('hello')

If I attempt to use the same name this outside the class definition, it will fail: 如果我尝试在类定义之外使用相同的名称,它将失败:

>>> x = X()
>>> x.__f()
Traceback (most recent call last):
  File "test.py", line 7, in <module>
    x.__f()
AttributeError: 'X' object has no attribute '__f'

Instead, Python uses _ClassName__PrivateMethod . 相反,Python使用_ClassName__PrivateMethod I can still call this pseudo-private function outside the class definition using the following: 仍然可以使用以下方法在类定义之外调用此伪私有函数:

>>> x._X__f()
hello

See Why are Python's 'private' methods not actually private? 请参阅为什么Python的“私有”方法实际上不是私有的? for some more useful information. 有关更多有用的信息。

Note, of course, that just because something is possible does not mean it is a good idea . 注意,当然,仅仅因为有可能发生并不意味着它是一个好主意 There is a reason why a well-designed class has private functions: these are internals that are not meant to be safely interacted with by outside functions. 有一个精心设计的类具有私有功能的原因:这些是内部函数,不能与外部函数安全地进行交互。

Python implements psuedo-private methods by munging method names that start with two underscores but don't end with underscores. Python通过修改以两个下划线开头但不以下划线结尾的方法名称来实现伪私有方法。 It Just adds the class name to the front. 它只是将类名添加到前面。

>>> class Foo(object):
...     def __private(self):
...         print('secret')
... 
>>> dir(Foo)
['_Foo__private', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']

Notice the _Foo__private method name. 注意_Foo__private方法名称。 You can just call that name. 您可以叫这个名字。

>>> Foo()._Foo__private()
secret

Things get weird with inheritance. 继承使事情变得怪异。 Notice below that the subclass has two private methods. 注意下面的子类有两个私有方法。 Subclasses need to be aware of the munging not to be surprised. 子类需要意识到这种担心,不要感到惊讶。 If you use a private method you may find you mess up anyone who inherits from the class and still wants to work with your code. 如果您使用私有方法,您可能会发现您弄乱了所有从该类继承但仍希望使用您的代码的人。

>>> class Bar(Foo):
...     def __private(self):
...         print('secret 2')
... 
>>> dir(Bar)
['_Bar__private', '_Foo__private', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']

Private methods are not part of an implementor's public interface and may be changed at any time without violating the public interface. 私有方法不是实现者的公共接口的一部分,并且可以随时更改而不会违反公共接口。 You can use them, but be aware that all hack rules apply. 您可以使用它们,但请注意所有黑客规则都适用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM