[英]how to access property like dict.get('key') in python Class
class Investor:
def __init__(self, profile):
self.profile = profile
def __getitem__(self, item):
return self.profile[item]
只需通過Investor['name']
訪問投資者資料是可以的,但是當我使用get()
Investor.get('name')
時出現錯誤
引發: AttributeError: 'Investor' object has no attribute 'get'
我知道我可以通過在投資者類中添加get()
方法來解決此問題,但這是正確的方法嗎? 還是還有其他特殊方法__get__
或其他什么方法?
標准get也具有默認值。 因此,這將是完整版本:
def get(self, item, default=None):
return self.profile.get(item, default=default)
至於這是正確的,據我所知,沒有更好的方法,因此默認情況下是這樣。
您為什么不只定義一個get
函數?
def get(self, item):
return self.profile.get(item)
如前所述,尚不存在特殊的“獲取”功能,您可以從對象類繼承。 要獲得所需的功能,您需要實現自己的“獲取”功能。
如果您實際上想創建很多類似於Investor的類,並且都具有get()函數,那么您應該創建一個超類供Investor繼承。
class Person(object):
def __init__(self, profile):
self.profile = profile
def get(self, item):
if item in self.profile:
return self.profile[item]
class Investor(Person):
def __init__(self, profile):
super().__init__(profile)
使用@property怎么樣?
class Investor:
def __init__(self, profile):
self._profile = profile
@property
def profile(self):
return self._profile
if __name__ == "__main__":
inv = Investor(profile="x")
print(inv.profile)
給出:
x
您可以使用的最簡單的解決方案是在__getitem__
方法中使用try:#code except: #code
塊。例如:
class Investor:
def __init__(self, profile):
self.profile = profile
def __getitem__(self, item):
try:
return self.profile[item]
except:
return 0
`
這將幫助您獲得像功能一樣的字典get()方法,而不必添加新的get()方法。
假設您有一個investor_object
,例如:
investor_object = Investor({'name': 'Bob', 'age': 21})
您可以執行以下任一操作:
investor_object.profile['name']
要么
investor_object.profile.get('name')
給出:
Bob
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.