2.5. Namespace
Functions and Classes can be namespaces
Functions can be nested in functions
Functions can be nested in classes
Classes can be nested in functions
The same for methods
2.5.1. Example
class MyClass:
class MyNestedClass:
...
def myfunction():
class MyNestedClass:
...
class MyClass:
def mymethod(self):
def myfunction():
...
2.5.2. Inner Functions
def run():
firstname = 'Mark'
lastname = 'Watney'
def run():
firstname = 'Mark'
lastname = 'Watney'
def hello():
print(firstname, lastname)
def run():
firstname = 'Mark'
lastname = 'Watney'
def hello():
print(firstname, lastname)
class Astronaut:
pass
def run():
firstname = 'Mark'
lastname = 'Watney'
def hello():
print(firstname, lastname)
class Astronaut:
firstname = 'Mark'
lastname = 'Watney'
def hello(self):
print(self.firstname, self.lastname)
2.5.3. Inner Classes
class User:
def __init__(self, firstname, lastname):
self.firstname = firstname
self.lastname = lastname
def login(self):
if not in DATABASE:
raise self.DoesNotExist
class DoesNotExist(Exception):
pass
try:
user = User('Mark', 'Watney')
user.login()
except User.DoesNotExists:
print('User does not exist')
class Person(models.Model):
firstname = ...
lastname = ...
class Meta:
ordering = ['lastname']