繁体   English   中英

如何在python类中访问dict.get('key')之类的属性

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM