030 Class Body Scope
030 Class Body Scope
030 Class Body Scope
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)
# module1.py
class Python:
kingdom = 'animalia'
phylum = 'chordata' def callable_1(self, species):
family = 'pythonidae' self.species = species
__init__ = callable_1
à when Python looks for a symbol in a function, it will therefore not use the class body scope!
©2019 MathByte Academy
In practical terms…
def monthly_interest(self):
return self.balance * self.APY