Python local variables in methods

I am learning Python 3 and I have a very fundamental question regarding Object Oriented Programming in Python. Here is my code.

class pet:
    number_of_legs = 0
    def count_legs(self):
        print("I have %s legs" %dog.number_of_legs)

dog = pet()
dog.number_of_legs = 4
dog.count_legs()

      

This code prints:

I have 4 legs

      

Why doesn't the count_legs method give an error like "Unknown variable dog in print". The variable dog exists outside of the class.

How does this code work? What is the motivation behind this behavior?

+3


source to share


1 answer


dog

considered global at runtime; if you named your variable differently, the code would generate an error:

>>> class pet:
...     number_of_legs = 0
...     def count_legs(self):
...         print("I have %s legs" %dog.number_of_legs)
... 
>>> cat = pet()
>>> cat.number_of_legs = 4
>>> cat.count_legs()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in count_legs
NameError: name 'dog' is not defined
>>> dog = cat
>>> cat.count_legs()
I have 4 legs

      

This makes it easier to refer to other globals in the module that are defined later; this includes recursive functions:

def fib(n):
    if n <= 1: return n
    return fib(n - 1) + fib(n - 2)

      



There fib()

is no global name in the definition yet fib

; only when the function object has been created is the global added. If the name should have existed, you first get the code, for example:

fib = None  # placeholder for global reference

def fib(n):
    if n <= 1: return n
    return fib(n - 1) + fib(n - 2)

      

and it's just noise.

+10


source







All Articles