python - What happened to the self variable when it's passed into a new function? -
this question has answer here:
- what purpose of self? 17 answers
i trying decipher code posted few years on here: how implement binary search tree in python?
the part confused section:
class node: def __init__(self, val): self.l_child = none self.r_child = none self.data = val def binary_insert(root, node): if root none: root = node else: if root.data > node.data: if root.l_child none: root.l_child = node else: binary_insert(root.l_child, node) else: if root.r_child none: root.r_child = node else: binary_insert(root.r_child, node)
the class , functions called doing this:
r = node(3) binary_insert(r, node(7)) binary_insert(r, node(1)) binary_insert(r, node(5))
my question is: happened self.data when passed binary_insert function? did node.data , root.data come from?
python uses self way class reference own attributes. python implicitly fills self class instance once method called of instance.
what happened self.data when passed binary_insert function?
nothing. instance of node
object passed binary_searach
function. node
object passed function, still has attributes of node
object, including self.data
.
where did node.data , root.data come from?
as can see, function takes 2 instances of node
object arguments. 2 node objects passed function still have attributes of original node
class. use different alias. can observed directly printing out type of root
, node
parameters:
at begining of function can print types of root
, node
:
def binary_insert(root, node): print("the type of root is:", type(root)) print("the type of node is:", type(node)) ...
which when called outputs:
the type of root is: <class 'node'> type of node is: <class 'node'> type of root is: <class 'node'> type of node is: <class 'node'> type of root is: <class 'node'> type of node is: <class 'node'> type of root is: <class 'node'> type of node is: <class 'node'>
Comments
Post a Comment