2.2. Namespace

2.2.1. Rationale

  • 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.2.2. Example

class MyClass:
    class MyNestedClass:
        ...
def myfunction():
    class MyNestedClass:
        ...
class MyClass:
    def mymethod(self):
        def myfunction():
            ...

2.2.3. 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.2.4. 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']

2.2.5. Assignments

Todo

Create assignments