I am learning Python 3 and I have 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 count_legs method does not give error like "Unknown variable dog in print." The variable dog exist outside the class.
How this code is working ? What is motivation behind such behavior ?
dog is looked up as a global at runtime; had you named your variable differently the code would have thrown 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 easy 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)
When defining fib() there is no global name fib yet; only when the function object has been created is the global added. If the name had to exist first you'd end up with code like:
fib = None # placeholder for global reference
def fib(n):
if n <= 1: return n
return fib(n - 1) + fib(n - 2)
and that is just noise.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With