0 votes
in Python by
What are nolocal and global keywords used for?

1 Answer

0 votes
by

These two keywords are used to change the scope of a previously declared variable. nolocal is often used when you need to access a variable in a nested function:

def func1():

    x = 5

    def func2():

        nolocal x

        print(x)

    func2()

global is a more straightforward instruction. It makes a previously declared variable global. For example, consider this code:

x = 5

def func1():

    print(x)

func1()

> 5

Since x is declared before function call, func1 can access it. However, if you try to change it:

x = 5

def func2():

    x += 3

func2()

> UnboundLocalError: local variable 'c' referenced before assignment

To make it work, we need to indicate that by x we mean the global variable x:

x = 5

def func2():

    global x

    x += 3

func2()

What is the difference between classmethod and staticmethod?

Both of them define a class method that can be called without instantiating an object of the class. The only difference is in their signature:

class A:

    @staticmethod

    def func1():

        pass

    

    @classmethod

    def func2(cls):

        pass

As you can see, the classmethod accepts an implicit argument cls, which will be set to the class A itself. Once common use case for classmethod is creating alternative inheritable constructors.

Related questions

0 votes
asked Sep 29, 2021 in Python by john ganales
0 votes
asked Jan 1, 2021 in Python by SakshiSharma
...