I know how to add a function to a python dict:
def burn(theName):
return theName ' is burning'
kitchen = {'name': 'The Kitchen', 'burn_it': burn}
print(kitchen['burn_it'](kitchen['name']))
### output: "the Kitchen is burning"
but is there any way to reference the dictionary's own 'name' value without having to name the dict itself specifically? To refer to the dictionary as itself?
With other languages in mind I was thinking there might be something like
print(kitchen['burn_it'](__self__['name']))
or
print(kitchen['burn_it'](__this__['name']))
where the function could access the 'name' key of the dictionary it was inside.
I have googled quite a bit but I keep finding people who want to do this:
kitchen = {'name': 'Kitchen', 'fullname': 'The ' ['name']}
where they're trying to access the dictionary key before they've finished initialising it.
TIA
CodePudding user response:
You can extend dict
object with your custom class, like this:
class MyDict(dict):
def __init__(self, *args, **kwargs):
self["burn_it"] = self.burn
super().__init__(*args, **kwargs)
def burn(self):
return self["name"] " is burning"
kitchen = MyDict({'name': 'The Kitchen'})
print(kitchen['burn_it']()) # The Kitchen is burning
print(kitchen.burn()) # The Kitchen is burning
CodePudding user response:
You cannot know which object reference the function.
A simple example, image the following:
def burn(theName):
return theName ' is burning'
kitchen = {'name': 'The Kitchen', 'burn_it': burn}
garage = {'name': 'The Garage', 'burn_it': burn}
burn
is referenced both in kitchen
and garage
, how could it "know" which dictionary is referencing it?
id(kitchen['burn_it']) == id(garage['burn_it'])
# True
What you can do (if you don't want a custom object) is to use a function:
def action(d):
return d['burn_it'](d['name'])
action(kitchen)
# 'The Kitchen is burning'
action(garage)
# 'The Garage is burning'
with a custom object:
class CustomDict(dict):
def __init__(self, *arg, **kwargs):
super().__init__(*arg, **kwargs)
def action(self):
return self['burn_it'](self['name'])
kitchen = CustomDict({'name': 'The Kitchen', 'burn_it': burn})
kitchen.action()
# 'The Kitchen is burning'