简体   繁体   中英

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]

It is ok to access Investor profile by simply Investor['name'] , But it comes to an error when I use get() Investor.get('name')

Raised: AttributeError: 'Investor' object has no attribute 'get'

I know I can fix it by adding a get() method to Investor Class, but is it a right way to do? or are there any other special method __get__ or whatever?

The standard get has a default as well. So this would be the full version:

def get(self, item, default=None):
    return self.profile.get(item, default=default)

As for this being proper, as far as I know there isn't any better way so it is by default.

Why don't you just define a get function?

def get(self, item):
    return self.profile.get(item)

As mentioned, there isn't a special "get" function which already exists and you can inherit from the object class. To get the functionality you want, you need to implement your own "get" function.

If you actually want to create a lot of similar classes to Investor which all have a get() function, then you should create a superclass for Investor to inherit from.

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)

How about using @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)

Gives:

x

The most simple solution that you can have is to use try:#code except: #code block in __getitem__ method.For ex:

class Investor:
    def __init__(self, profile):
       self.profile = profile

    def __getitem__(self, item):
       try:
         return self.profile[item]
       except:
         return 0

`

This will help you to get dictionary get() method like features without having to add new get() method.

Assuming you have an investor_object , like:
investor_object = Investor({'name': 'Bob', 'age': 21})

You can do either:
investor_object.profile['name']
or
investor_object.profile.get('name')

Gives:
Bob

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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