[英]How to return with a python method A NEW class object?
I have some questions with respect to the not working code below: 我对以下不起作用的代码有一些疑问:
__init__
take as an argument a schema and a list
(which is a list
of dictionaries - where I do my search)? __init__
可以将模式和list
作为参数(这是一个字典list
- 我在哪里搜索)? 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
视为空 - 未找到电影。
DataBase
object call DataBase(movies, schema)
, where movies
and schema
are the parameters of the __init__()
method of the class. DataBase
对象调用DataBase(movies, schema)
,其中movies
和schema
是类的__init__()
方法的参数。 __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__()
方法)。 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.