Python类存储和引用实例

2024-09-29 19:06:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建一个类,其中包含:namespace、filepath和selectionset data(list)数据。你知道吗

我有一个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数据?你知道吗

抱歉,如果我的一些术语是错误的!你知道吗

干杯。你知道吗


Tags: 数据self记录johnnamespacetempfilepathmainlist
3条回答

虽然它通常被用作一个成熟的网站框架,但是Django model与您在这里尝试做的关于过滤的工作非常接近:

from django.db import models


class CHRecord(models.Model):
    namespace = models.CharField(max_length=32)
    filepath = models.FileField()
    # Not sure what this represents in your question, but if you use
    # PostgreSQL as your backend, might want an Array
    sel_sets = models.CharField(max_length=512)

# Saves a row to a database (local SQLite by default)
CHRecord.objects.create(namespace="John:", filepath="C:/temp/", sel_sets="xyz")

# Get matching rows translating to a SQL query
CHRecord.objects.filter(namespace__contains="John")

如果需要强制使用唯一值,可以使用字典。只需将键设置为唯一值或应该唯一的值。你知道吗

这应该比循环运行得更快,但是如果键不是唯一的,它将覆盖数据。你知道吗

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)

浏览列表并匹配namespace属性。你知道吗

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

相关问题 更多 >

    热门问题