-1

In the Python code portion of Inorder predecessor and successor for a given key in BST, something of this sort is done. Can someone explain this part of code?

P.S. I know what static variables are, it's just that its implementation in the way shown is confusing me.

# Static variables of the function findPreSuc
findPreSuc.pre = None
findPreSuc.suc = None
2
  • 2
    Static variables are just a convenient way of naming a variable such that it is associated with that class/function. That way, you don't have to manually specifiy the scope of a variable (like with global) to use the variables pre and suc in the function. Commented Jun 20, 2021 at 10:11
  • 1
    ...and since they are part-of / attached-to the function, they are not allocated each time the function is called like local variables would be (i.e. they're statically allocated). Commented Jun 20, 2021 at 12:04

1 Answer 1

0

In Python, everything is object. And every object has member fields that can be accesed. This is stored in special field called __dict__. You can acces object attributes in various ways:

obj.field # direct attribute access
obj.__dict__["field"] # attribute dictionary access
getattr(obj, "field") # get attribute

Functions are objects too and thus they also have a __dict__ field. But they have unique behavior from other objects - if you try access field that doesn't exists with normal object, you will get error. If you try same thing with function, function will add new field instead (like how function create new local variables)

TL;DR: functions are objects too, and they can have fields like objects. These fields don't change between callings

Sign up to request clarification or add additional context in comments.

2 Comments

Functions do not have the unique behavior you describe. If you access an attribute that doesn't exist they throw an AttributeError as well: def a(): pass; a.b raises AttributeError: 'function' object has no attribute 'b'
Actually they're called attributes, not fields.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.