繁体   English   中英

如何使用python方法返回一个新的类对象?

[英]How to return with a python method A NEW class object?

我对以下不起作用的代码有一些疑问:

  1. 如何使方法搜索返回一个新的数据库对象?
  2. __init__可以将模式和list作为参数(这是一个字典list - 我在哪里搜索)?
  3. 如何避免一次又一次地在搜索方法中编写类似的函数,导致数据库中有很多字段名。

在此先感谢您的帮助。

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**

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

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视为空 - 未找到电影。

  1. 返回DataBase对象调用DataBase(movies, schema) ,其中moviesschema是类的__init__()方法的参数。
  2. __init__()可以根据需要使用尽可能多的位置参数,但是记得将它们的对象分配给__init__()体内的适当名称,以便以后可以使用它们(请参阅我的类中的__init__()方法)。
  3. 为了避免在search()方法中重复搜索模式,只需使用field参数作为匹配数据库中每条记录的键,并在两种情况下拆分问题:一个用于范围搜索,另一个用于纯搜索(参见下面的search()方法)。 请记住解决不匹配的情况:在我的实现中,我只返回一个空的DataBase对象。 您还应该解决无效搜索键的情况:在我的实现中,我返回None

下面的test()函数提供了一个数据库和三个搜索,既简单又在一个范围内。

您应该将collections.namedtuple视为数据库记录的替代表示。

class DataBase():

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

    def __str__(self):
        return str(self.movies)

    def search(self, field, from_value, to_value=None):
        if field in self.schema:
            matches = []
            if to_value:
                for movie in self.movies:
                    if movie[field] in range(from_value, to_value):
                        matches.append(movie)
            else:
                for movie in self.movies:
                    if movie[field] == from_value:
                        matches.append(movie)
            return DataBase(matches, self.schema)
        else:
            return None

def test():
    schema = [ "title", "year", "rating" ]
    movies = [
        { "title":"Star Wars: The Empire Strikes Back",       "year":1980, "rating":3 },
        { "title":"Serenity",                                 "year":2005, "rating":5 },
        { "title":"Scarface",                                 "year":1983, "rating":4 },
        { "title":"Harry Potter and the Philosopher's Stone", "year":2001, "rating":2 },
        ]

    db = DataBase(movies, schema)
    print(db.search("title", "Scarface"))
    print(db.search("year", 2000, 2008))
    print(db.search("rating", 4, 6))
    print(db.search("title", "The Last Emperor"))
    print(db.search("invalid", "value"))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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