class MyClass(object):
code_mapping = {...}
def get_name(code):
code = code_mapping[code]
...
In this piece of code, it complains that 'code_mapping is not defined'. Isn't code_mapping is accessible to everything within MyClass?
class MyClass(object):
code_mapping = {...}
def get_name(code):
code = code_mapping[code]
...
In this piece of code, it complains that 'code_mapping is not defined'. Isn't code_mapping is accessible to everything within MyClass?
Initialize it with self
. This will make it accessible by any function in the class by passing it with self.<variable>
and then passing self
as a function argument to anything you want to pass the variable to.
class MyClass(object):
def __init__(self):
self.code_mapping = {...} # if this will be a hard coded
def get_name(self):
code = self.code_mapping[code]
...
Or you could do:
class MyClass(object):
def __init__(self, code_mapping):
self.code_mapping = code_mapping
def get_name(self):
code = self.code_mapping[code]
...
if you'd like to pass some code mapping as an argument to your class at its instantiation.
To create a class object from this where you want {'code1' : 'name'}
you then initiate a class object like this:
code1 = MyClass({'code1' : 'name'})
And then {'code1' : 'name'}
will be what is carried forth into whatever get_name()
does and the value of code
in get_name
will be name
.