【问题标题】:Load All Method Results in Python Class to Dictionary将 Python 类中的所有方法结果加载到字典
【发布时间】:2015-03-06 16:05:26
【问题描述】:

如果我有一个像下面这样的类(实际上,它有更多的方法),并且我想将每个方法的结果加载到字典中,有没有更快的方法来做features_to_dict,如果我添加新方法?

from bs4 import BeautifulSoup

class CraigsPage():

    def __init__(self, page_file):
        self._page = open(page_file).read()
        self.soup = BeautifulSoup(self._page)
        self.title = self.soup.title.string
        self.body = str(self.soup.find('section', id='postingbody'))

    def get_title_char_count(self):
        return len(list(self.title.replace(' ', '')))

    def get_title_word_count(self):
        return len(self.title.split())

    def get_body_char_count(self):
        return len(list(self.body.replace(' ', '')))

    def features_to_dict(self):
        feature_dict = {}
        feature_dict['title_char_count'] = self.get_title_char_count()
        feature_dict['title_word_count'] = self.get_title_word_count()
        feature_dict['body_char_count'] = self.get_body_char_count()
        return feature_dict

【问题讨论】:

标签: python class dictionary methods


【解决方案1】:

inspect 模块对于这类东西很方便:

def features_to_dict(self):
    members = inspect.getmembers(self, inspect.ismethod)
    return {name: method() for name, method in members if name.startswith('get')}

【讨论】:

    【解决方案2】:

    Python 类具有__dict__ 属性,该属性将类的所有属性存储为字典。下面的 sn-p 遍历 __dict__ 试图找到以 get 开头的函数,并自动运行它们,并将结果存储到一个字典中:

    class A(object):
        def get_a(self):
            return 1
    
        def get_b(self):
            return 2
    
        def features_to_dict(self):
            self.d = {}
            for f_name, f in A.__dict__.iteritems():
                if 'get' in f_name:
                    self.d[f_name[4:]] = f(self)
    a = A()
    a.features_to_dict()
    print a.d
    

    这将返回{'a': 1, 'b': 2}

    【讨论】:

      【解决方案3】:

      使用 dir() 方法代替 dict 属性。

      class A(object):
          def method(self):
              return 123
          def call_all(self):
              skip = dir(object) + ['call_all']
              results = {}
              for key in dir(self):
                  if key not in skip and callable(getattr(self, key)):
                      try:
                          results[key] = getattr(self, key)()
                      except Exception as e:
                          results[key] = e
              return results
      

      【讨论】:

      • dir() 比 dict 有什么优势?
      • 类的__dict__ 仅包含该类的属性,不包含继承的属性。函数dir 返回所有属性的列表,包括继承的。所以,这个变体也适用于这个类的所有后代。
      • 我明白了。是否存在调用我不知道的方法的风险?
      • 谢谢。所以你觉得一个人会完成同样的事情吗?
      【解决方案4】:

      有点简单的方法,根本不使用自省并明确定义要调用的方法:

      class A(object):
          methods_to_call = [
              "get_title_char_count",
              "get_title_word_count",
              "get_body_char_count",
          ]
          ...
          def features_to_dict(self):
              feature_dict = {}
              for method in self.methods_to_call:
                  feature_dict[method[4:]] = getattr(self, method)()
      
              return feature_dict
      

      【讨论】:

      • 不过,这根本不是模块化的,每次添加方法时都需要更新
      猜你喜欢
      • 2013-11-14
      • 2015-08-20
      • 2018-04-30
      • 2018-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-14
      • 1970-01-01
      相关资源
      最近更新 更多