简体   繁体   中英

Accessing private methods from inherited class in python

I want to follow good programming practice, so i am kind of stuck at this questions:

Lets say i have Class root,

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

   def __str__(self):
     return self._root_tree

   def _test(self):
      return 'test'

lets say i create a class called 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'

Then in Class Cherry, can i do the following

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()

Basically calling __str__() _new_fun() and _test() in the Cherry class valid (good practice).

You can, but in this example it would be better to just call str(another_tree) . In general you shouldn't call the double-underscore methods directly unless you're doing something that specifically relates to their implementation (eg, calling a superclass implementation from within a subclass implementation). Mostly the double-underscore methods exist to let the class behave in a certain way in a more "normal" context, and you should use that normal context for normal purposes. For instance, __str__ exists to let the class do the right thing when you call str() on it, so you should call str() on it instead of calling __str__ directly.

As for single-underscore methods, it's generally not a good idea to call those unless you wrote them. There's no "penalty" for doing so, but by convention the single underscore indicates methods that aren't part of a public API. So if you use them, you run the risk of having your code break if the library you're using is updated and those underscore methods disappear or change.

It depends on what your design declares as the logical interface for the methods of these classes.

If you somehow, somewhere specify that you are returning non-instance then what you do is perfectly fine. If you are creating implicit expectation that method returns an instance of Cherry and you are returning Oak then you are introducing room for serious bugs.

In general, reserve the __method__ convention for the inner workings of your class and for recasting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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