从python中的继承类访问私有方法

时间:2012-08-02 02:15:17

标签: python class inheritance

我想遵循良好的编程习惯,所以我有点坚持这个问题:

假设我有Class root,

Class root(Object):
   def __init__(self):
     self._root_tree = 'Base'

   def __str__(self):
     return self._root_tree

   def _test(self):
      return 'test'

假设我创建了一个名为Oak

的类
Class Oak(root):
    def __str__(self):
      return 'Oak'
    def _test(self):
      return 'Oak_test'
    def _new_fun(self):
      return 'new_func_only_in_oak'

然后在Class Cherry,我可以做以下

Class Cherry(root):
    def _grab_trees(self,another_tree): #another_tree is a Oak object
      other_tree = another_tree.__str__() #this will return Oak
      return 'The other three is: ' + other_tree
    def _test2(self,another_tree):
      return another_tree._test()
    def _testing_new(self,another_tree):
      return another_tree._new_fun()

基本上在Cherry课程中调用__str__() _new_fun()_test()是有效的(良好实践)。

2 个答案:

答案 0 :(得分:0)

您可以,但在此示例中,最好只拨打str(another_tree)。通常,除非您正在执行与其实现特定相关的操作(例如,从子类实现中调用超类实现),否则不应直接调用双下划线方法。大多数情况下,双下划线方法的存在是为了让类在更“正常”的上下文中以某种方式运行,并且您应该将该正常上下文用于正常目的。例如,__str__存在,当您在其上调用str()时,该类会做正确的事情,因此您应该在其上调用str(),而不是直接调用__str__。< / p>

对于单下划线方法,除非你编写它们,否则调用它们通常不是一个好主意。这样做没有“惩罚”,但按照惯例,单个下划线表示不属于公共API的方法。因此,如果您使用它们,如果您正在使用的库已更新且这些下划线方法消失或更改,则可能会导致代码中断。

答案 1 :(得分:0)

这取决于您的设计声明为这些类的方法的逻辑接口。

如果你以某种方式,某处指定你正在返回非实例,那么你所做的就完全没问题了。如果您正在创建隐式期望方法返回Cherry的实例并且您正在返回Oak,那么您将为严重错误引入空间。

一般情况下,保留班级内部工作的__method__约定和重铸。