You are on page 1of 5

©2019 MathByte Academy

Nested scopes in Class definitions à module has its own (global) scope
contains Python, p

# module1.py
à class body has its own scope
class Python: contains kingdom, phylum , family , __init__
, say_hello
kingdom = 'animalia'
phylum = 'chordata' à what about the scope of functions
family = 'pythonidae' defined in the body of a class?

def __init__(self, species): à turns out they are NOT nested inside the
self.species = species class body scope

def say_hello(self):
return 'ssss…' à symbols __init__, say_hello are in the class
body scope
p = Python('monty')
à but functions themselves are nested in the
class's containing scope
(module1 in this example)

©2019 MathByte Academy


Think of it this way

# module1.py

class Python:

kingdom = 'animalia'
phylum = 'chordata' def callable_1(self, species):
family = 'pythonidae' self.species = species

__init__ = callable_1

say_hello = callable_2 def callable_2(self):


return 'ssss…'
p = Python('monty')

à when Python looks for a symbol in a function, it will therefore not use the class body scope!
©2019 MathByte Academy
In practical terms…

class Account: this works because APR and


COMP_FREQ = 12 COMP_FREQ are symbols in the
APR = 0.02 # 2% same (class body) namespace
APY = (1 + APR/COMP_FREQ) ** COMP_FREQ - 1

def __init__(self, balance):


this works because we used self.APY
self.balance = balance

def monthly_interest(self):
return self.balance * self.APY

@classmethod this works because we used cls.APY


def monthly_interest_2(cls, amount):
return amount * cls.APY

@staticmethod this works because we used Account.APY


def monthly_interest_3(amount):
return amount * Account.APY
this will fail if APY is not defined in this function's
def monthly_interest_3(self): scope or in any enclosing scope
return self.amount * APY
©2019 MathByte Academy
BEWARE: This can produce subtle bugs!
Coding

©2019 MathByte Academy

You might also like