In static languages – it makes since to put the class variable at the top of the Class. However, since Python is dynamic, it can’t know about the functions until it processes them.
class AwsProcessor:
service_dict = {'s3': process_s3, 'ebs': process_ebs}
def __init__(self, processing_service):
self.service = processing_service
def process_ebs(self):
pass
def process_s3(self):
pass
This gives error
File "c:\aws-scripts\class AwsProcessor.py", line 1, in <module>
class AwsProcessor:
File "c:\aws-scripts\class AwsProcessor.py", line 2, in AwsProcessor
service_dict = {'s3': process_s3, 'ebs': process_ebs}
NameError: name 'process_s3' is not defined
If you move the variable below the function def it will run without error
class AwsProcessor:
def __init__(self, processing_service):
self.service = processing_service
def process_ebs(self):
pass
def process_s3(self):
pass
service_dict = {'s3': process_s3, 'ebs': process_ebs}
to call such a function – you need to reference the class namespace.
def process_services(self):
AwsProcessor.service_dict[self.service](self)
