首页 > 解决方案 > How to return with a python method A NEW class object?

问题描述

I have some questions with respect to the not working code below:

  1. How to make a method search return a New Database object?
  2. Can __init__ take as an argument a schema and a list (which is a list of dictionaries - where I do my search)?
  3. How to avoid writing similar function in search method again and again, cause there are a lot of field names in the database.

Thanks in advance for your help.

class DataBase():  
# Searches Movies by title and gives its entire info :( (stupid)
def __init__(self, movies, schema):
    pass


def search(self, field_name, field_value1, field_value2=None):
    if field_name=='title':
        mov=[]
        for movie in movies:
            if field_value1 == movie['movie_title']:
                mov.append(movie)
        return mov

    if field_name=='year':
        for movie in movies:
            if field_value2:
                if movie['title_year'] in range (field_value1, field_value2+1):
                     return movie['movie_title'],movie['title_year']

            else:
                if movie['title_year']==field_value1:
                     return movie['movie_title'],movie['title_year']

    if field_name=='actor_1_name':
        mov=[]
        for movie in movies:
            if field_value1 == movie['actor_1_name']:
                mov.append(movie)
        return mov
        **strong text**

标签: pythonclassoopmethods

解决方案


目前还不清楚您要做什么,如果没有输入示例和所需结果的示例,很难解释,但这可能很接近。

class DataBase():  
    def __init__(self, movies, schema):
        self.movies = movies
        self.schema = schema

    def search(self, field_name, field_value1, field_value2=None):
        search_result = []
        for movie in self.movies:
            if field_value2:
                if movie[field_name] in range((field_value1, field_value2+1)):
                    search_results.append(movie)
            else:
                if movie[field_name] == field_value1:
                    search_results.append(movie)

        return DataBase(search_results, self.schema)

您甚至可能希望简化搜索中的比较。您可以为(两种)不同类型的比较定义辅助函数;根据参数选择要使用的比较;然后在搜索中使用所选功能。

...

    def search(self, field_name, field_value1, field_value2=None):

        # comparison types    
        def range_comparison(movie, start=field_value1, end=field_value2):
            return movie[field_name] in range(start, end+1)
        def equality_comparison(movie, name=field_value1):
            return movie[field_name] == name

        # which comparison to use    
        comparison = range_comparison if field_value2 else equality_comparison

        search_result = []
        for movie in self.movies:
            if comparison(movie):
                search_results.append(movie)
        # or
        # search_results = [movie for movie in movies if comparison(movie)]
        return DataBase(search_results, self.schema)

出于某种原因,这对我很有吸引力,因为它将比较类型的逻辑与实际搜索分开。


它不考虑为search_results空 - 没有找到电影。


推荐阅读