Topic: Functions and their scopes in Python. Create user functions What is Python Scope?



Yüklə 41,02 Kb.
səhifə4/5
tarix24.10.2023
ölçüsü41,02 Kb.
#130884
1   2   3   4   5
Topic2

locals()
Another function is locals(), which is related to scope and namespaces in Python. It updates and returns a dictionary with a copy of the current state of the local Python scope. When you call locals() within a function block, names that can be accessed locally from the function will be returned. Let us understand locals() with the help of a code.
# Without using local variables
def test_1():
print("No local variable : ", locals())
# Using local variables
def test_2():
Language = "Python Programming"
print("Local variable: ", locals())
test_1()
test_2()
OUTPUT:
No local variable : {}
Local variable : {'Language': 'Python Programming'}
Copy Code
Let's have a look at one more code:
def test():
score = 10
locals()['score'] = 200
print('The Score is:', score)
test()
OUTOUT:
The Score is: 10
Copy Code
dir()
An important built-in function, dir () relates to scope and namespaces in python. It returns a list of valid attributes. Moreover, dir() function behavior differs with a different type of object, as it targets to generate the most relevant one instead of complete information. Let us understand dir() with the help of a code.
scores = [5, 2, 3]
print(dir(scores))
print('\n Return values from the empty dir()')
print(dir())
OUTPUT:
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
Return values from the empty dir()
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'scores']
Copy Code
vars()
The vars() function is another in-built function related to scope and namespaces in Python. It returns __dict__ attribute for modules, classes, instances, or objects. It is important to note that the __dict__ is a special dictionary used by Python to implement namespaces. Remember, if you miss writing the vars() attribute, it will merely behave like locals(). Let us understand vars() with the help of a code.
class Scores:
def __init__(self, Roll_1 = "Alice", Roll_2 = "Bella", Roll_3 = "Cindrella"):
self.Roll_1 = Roll_1
self.Roll_2 = Roll_2
self.Roll_3 = Roll_2
score = Scores()
print(vars(score))
OUTPUT:
{'Roll_1': 'Alice', 'Roll_2': 'Bella', 'Roll_3': 'Bella'}
Copy Code

Yüklə 41,02 Kb.

Dostları ilə paylaş:
1   2   3   4   5




Verilənlər bazası müəlliflik hüququ ilə müdafiə olunur ©muhaz.org 2024
rəhbərliyinə müraciət

gir | qeydiyyatdan keç
    Ana səhifə


yükləyin