Python类-存储并返回实例

时间:2019-04-12 17:31:19

标签: python class instance

我正在尝试创建一个包含以下内容的类:名称空间,文件路径和其中包含的selectionset数据(列表)数据。

我有一个UI,可以让我为输入的每个字符添加一个新的“记录”。

到目前为止,我已经知道了:

mainlist = []

class chRecord:
    def __init__(self, namespace, filepath, selSets =[]):
        self.namespace = namespace
        self.filepath = filepath
        self.selSets = selSets


aName = "John:"
aAge = "C:/temp/"
aSelSets = "Animation:stuff_Junk 0-10, 
animation:bob_jeff 10-30"

characterRecord = chRecord(aName,aAge,aSelSets)

mainlist.append(characterRecord)

aName = "John2:"
aAge = "C:/temp/"
aSelSets = "Animation:stuff_Junk2 0-10, 
animation:bob_jeff2 10-30"

characterRecord = chRecord(aName,aAge,aSelSets)

mainlist.append(characterRecord)

我的问题是我该如何搜索mainList来查找我想要的记录。即'John',然后找到名称空间,文件路径和selectionset数据?

很抱歉,如果我的术语在某些方面不正确!

干杯。

4 个答案:

答案 0 :(得分:1)

虽然它通常用作完善的网站框架,但Django model与您在此处要进行的过滤工作非常接近:

fn

答案 1 :(得分:0)

您将需要创建一个函数,该函数将记录列表和名称搜索作为参数。然后它将返回匹配的记录,您将可以从中获取更多信息。

示例:

mainlist = []


def find_record_by_name(records, name):
    for record in records:

        if record.namespace == name:
            return record


class chRecord:
    def __init__(self, namespace, filepath, selSets=[]):
        self.namespace = namespace
        self.filepath = filepath
        self.selSets = selSets


aName = "John:"
aAge = "C:/temp/"
aSelSets = "Animation:stuff_Junk 0-10, animation:bob_jeff 10-30"

characterRecord = chRecord(aName, aAge, aSelSets)

mainlist.append(characterRecord)

aName = "John2:"
aAge = "C:/temp/"
aSelSets = "Animation:stuff_Junk2 0-10,animation:bob_jeff2 10-30"

characterRecord = chRecord(aName, aAge, aSelSets)

mainlist.append(characterRecord)

selected_record = find_record_by_name(mainlist, "John:")

if selected_record:
    print(selected_record.namespace)
    print(selected_record.filepath)
    print(selected_record.selSets)

答案 2 :(得分:0)

浏览列表并匹配namespace属性。

for record in mainlist:
    if record.namespace == 'John':
        # the record is found, now you can access the attributes with `record.filepath`
        print(record)

答案 3 :(得分:0)

如果您需要强制使用唯一值,则可以使用字典。只需将键设置为唯一值或应该唯一的值即可。

这应该比循环快,但是如果键不是唯一的,它将覆盖数据。

mainlist = {}

class chRecord:
    def __init__(self, namespace, filepath, selSets =[]):
        self.namespace = namespace
        self.filepath = filepath
        self.selSets = selSets


aName = "John:"
aAge = "C:/temp/"
aSelSets = "Animation:stuff_Junk 0-10, animation:bob_jeff 10-30"

mainlist[aName] = chRecord(aName,aAge,aSelSets)
print(mainlist[aName].selSets)

aName = "John2:"
aAge = "C:/temp/"
aSelSets = "Animation:stuff_Junk2 0-10, animation:bob_jeff2 10-30"

mainlist[aName] = chRecord(aName,aAge,aSelSets)

print(mainlist.get('John2:').namespace)
print(mainlist.get('John2:').filepath)
print(mainlist.get('John2:').selSets)