简体   繁体   English

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

[英]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)? __init__可以将模式和list作为参数(这是一个字典list - 我在哪里搜索)?
  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**

It isn't really clear what you are trying to do, and it is hard to interpret without an example of the inputs and the desired result but this might be close. 目前还不清楚你要做什么,如果没有输入和期望结果的例子,很难解释,但这可能很接近。

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)

You might even want to simplify the comparisons in the search. 您甚至可能希望简化搜索中的比较。 you could define helper functions for the (two) different types of comparisons; 你可以为(两种)不同类型的比较定义辅助函数; choose which comparison to use based on the arguments; 根据参数选择要使用的比较; then use the chosen function in the search. 然后在搜索中使用所选的功能。

...

    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)

For some reason that appeals to me because it separates the logic of the type of comparison from the actual search. 由于某种原因,它吸引我,因为它将比较类型的逻辑与实际搜索分开。


It doesn't account for search_results being empty - no movies found. 它不会将search_results视为空 - 未找到电影。

  1. To return a DataBase object call DataBase(movies, schema) , where movies and schema are the parameters of the __init__() method of the class. 返回DataBase对象调用DataBase(movies, schema) ,其中moviesschema是类的__init__()方法的参数。
  2. __init__() can take as many positional parameters as you want, but remember to assign their object to appropriate names inside the __init__() body, so that you can use them later (see the __init__() method on my class). __init__()可以根据需要使用尽可能多的位置参数,但是记得将它们的对象分配给__init__()体内的适当名称,以便以后可以使用它们(请参阅我的类中的__init__()方法)。
  3. To avoid repeating the search pattern all over the search() method, just use the field parameter as a key for matching each record on the database, and split the problem in two cases: one for the range search, the other for the plain search (see search() method below). 为了避免在search()方法中重复搜索模式,只需使用field参数作为匹配数据库中每条记录的键,并在两种情况下拆分问题:一个用于范围搜索,另一个用于纯搜索(参见下面的search()方法)。 Remember to address the no-match case: in my implementation I just return an empty DataBase object. 请记住解决不匹配的情况:在我的实现中,我只返回一个空的DataBase对象。 You should also address the case of invalid search key: in my implementation I return None . 您还应该解决无效搜索键的情况:在我的实现中,我返回None

The test() function below provides a database and three searches, both simple and within a range. 下面的test()函数提供了一个数据库和三个搜索,既简单又在一个范围内。

You should consider collections.namedtuple as an alternative representation for database records. 您应该将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.

相关问题 python __new__方法如何返回字符串或unicode对象而不是类对象 - How can python __new__ method return a string or unicode object instead of class object 在python中模拟类对象方法的返回 - mocking a return of class object method in python 如何在Python中将方法中的内容返回给类 - How to return something from a method to a class in Python 如何从在 python 中使用补丁模拟的类的方法返回 MagicMock 对象 - How to return MagicMock object from a method of a class that was mocked using patch in python 如何在Python中返回相同的类对象 - How to return the same class object in Python 覆盖python方法以返回具有扩展数据的正确类的对象 - Overriding python method to return object of correct class with extended data Parent Class with new object, and new object in Subclass, object/method inheritance Python - Parent Class with new object, and new object in Subclass, object/method inheritance Python 如果我在python中扩展类,如何自动将结果作为新类返回? - If I extend a class in python, how to automatically return the result as the new class? 如何在 Python 中重新加载类对象的方法的代码? - How to reload the code of a method of class object in Python? 如何查找python对象是函数还是类方法? - How to find if python object is a function or class method?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM