![](/img/trans.png)
[英]python, dictionary value is object, can that object access its own key value from a function within itself?
[英]Can you access a python dictionary key's value from a function in that dictionary?
我知道如何將 function 添加到 python 字典中:
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"
但是有沒有辦法引用字典自己的“名稱”值而不必專門命名字典本身? 引用字典本身?
考慮到其他語言,我在想可能會有類似的東西
print(kitchen['burn_it'](__self__['name']))
或者
print(kitchen['burn_it'](__this__['name']))
function 可以訪問它所在字典的“名稱”鍵。
我用谷歌搜索了很多,但我一直在尋找想要這樣做的人:
kitchen = {'name': 'Kitchen', 'fullname': 'The ' + ['name']}
他們在完成初始化之前嘗試訪問字典鍵的位置。
TIA
您無法知道哪個 object 引用了 function。
一個簡單的例子,如下圖:
def burn(theName):
return theName + ' is burning'
kitchen = {'name': 'The Kitchen', 'burn_it': burn}
garage = {'name': 'The Garage', 'burn_it': burn}
kitchen
和garage
都引用了burn
,它怎么能“知道”哪個字典引用它?
id(kitchen['burn_it']) == id(garage['burn_it'])
# True
您可以做的(如果您不想要自定義對象)是使用 function:
def action(d):
return d['burn_it'](d['name'])
action(kitchen)
# 'The Kitchen is burning'
action(garage)
# 'The Garage is burning'
使用自定義 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'
您可以使用自定義 class 擴展dict
object,如下所示:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.