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)
如前所述,没有一个已经存在的特殊"get"函数,你可以从对象类继承。要获得所需的功能,您需要实现自己的"get"函数。
如果你真的想创建很多与 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