Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23247

in OOP Is it correct to pass an attribute to the method as a parameter?

$
0
0

I wrote a recursive program to print the values of a binary search tree from the smallest to the largest (in order) and it can be written in two ways:

  1. This can be written in such a way that the function receives the root as a parameter as follows:
class TreeNode:    def __init__(self, data):        self.data = data        self.left = None        self.right = Noneclass BinarySearchTree:    root = None    def in_order(self, root):        current = root        if current is None:            return        self.in_order(current.left)        print(current.data)        self.in_order(current.right)t1.in_order(t1.root)

The problem in this way is that the user has to give direct access to the root (t1.root)

  1. This can be written in such a way that the user does not have to give the root as a parameter, but we will have to write it as two functions:
    def in_order2(self):        self.inner_inorder(self.root)    def inner_inorder(self, current)        if current is None:            return        self.in_order(current.left)        print(current.data)        self.in_order(current.right)t1.in_order2()

Which form of writing is considered more correct?


Viewing all articles
Browse latest Browse all 23247

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>