用于数据和重构的Python类属性

2024-06-11 07:07:42 发布

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

对于以下问题,我没有找到好的建议: 我正在创建一个PyQt应用程序,希望每个项目的一个文件中都有持久数据(没有serveur,没有SQL)。你知道吗

我决定创建一个具有属性的类,然后实例化对象。然后我将这些对象存储在一个列表中(预期为<;500个对象,大多数项目为<;60个对象)。最后,我使用pickle模块将数据存储在一个驱动器上。你知道吗

  1. 这样做真的不好吗(类对象比dict列表更容易理解…)
  2. 我创建了以下代码

    class Item: position = ['key','a','b','c'] def__init__(self, key=None, a=None, b=None, c=None): self.key = key self.a = a self.b = b self.c = c 有没有办法避免重复k、a、b、c(我以后可能会添加很多)


Tags: 文件项目对象keyltselfnone应用程序
3条回答

你可以这样做:

class Item:
    position = ['key','a','b','c']
    def__init__(self, **kwargs):
        for key in Item.position:
            setattr(self,key,kwagrs.get(key, None))

这将使你的课堂违抗非常难以阅读。你知道吗

  1. 不,这不是一件坏事

  2. 因此,您可以避免重复:

class Item:
    params = {}
    def __init__(self, **kwargs):
        self.params = kwargs

现在,你可以

item = Item(first_name='Sylvain', last_name='Page')

有没有什么好的做法来代替存储实例列表?你知道吗

您指定的数据量不是很高,因此类的实例列表应该是可行的,但是有更好的方法来存储这些信息。你知道吗

  1. 如你所说的dict列表。你知道吗
  2. namedtuple的列表

口述

把格言伪装成目标

如果选择第一个选项,则可以创建一个充当类构造函数的函数,以保持类似的语法:

def Item(key=None, a=None, b=None, c=None):
    return {
        "key": key,
        "a": a,
        "b": b,
        "c": c
    }

额外的抽象级别增加了灵活性

您甚至可以创建一个函数,通过传递键列表来生成此类函数:

def ItemGenerator(*spec):
    def f(*args, **kwargs):
        args = dict(enumerate(args))
        return {k: kwargs.get(k, args.get(i, None)) for i, k in enumerate(spec)}
    return f

ItemGenerator()函数接受任意数量的字符串作为直接参数,而无需将它们包装到列表中。如果您只想给出一个列表作为参数,只需从def ItemGenerator(*spec):中删除*。它创建一个新函数,返回一个字典,字典的键是传递给ItemGenerator的参数,它们的值以None作为默认值。然后它会这样使用:

NOTE: dicts in python are unordered so you may see the arguments in a different order while printing the results to the screen, but their value will be assigned correctly. I've listed them ordered for clearness.

Item = ItemGenerator("key", "a", "b", "c")

# All default values
Item()                     # {"key": None, "a": None, "b": None, "c": None}
# Named and positional arguments
Item(a=1)                  # {"key": None, "a": 1,    "b": None, "c": None}
Item(1)                    # {"key": 1,    "a": None, "b": None, "c": None}
Item(key=1, a=2, b=3, c=4) # {"key": 1,    "a": 2,    "b": 3,    "c": 4   }
Item(1, 2, 3, 4, a=5)      # {"key": 1,    "a": 5,    "b": 3,    "c": 4   }
# Extra arguments
Item(1, 2, 3, 4, 5)        # {"key": 1,    "a": 2,    "b": 3,    "c": 4   }
Item(a=1, d=2)             # {"key": None, "a": 1,    "b": None, "c": None}

Item函数在开始时通过指定最终字典将拥有的键来生成,然后可以根据需要多次使用。调用它时,不提供为生成器指定的参数之一会将其值设置为None。位置参数和命名参数都可以使用,但命名参数优先。提供不在规范中的额外位置参数或命名参数会自动忽略它们。你知道吗

More technical description: the generator is returning a function thats captures both positional and named (key-word) arguments, and converting the positional ones to a dict indexed by position in order to be able to use dict.get(attrName, defaultValue). Then it uses a comprehension to return a dict whose keys are those defined in the generator and its values are first searched in the named arguments, secondly in the positional arguments and default to None if both of them are missing. The function generated is then being returned.

命名双

代替使用dict,您可以使用namedtuplePython2.7Python3.6),在那里您可以使用类似的方法来生成一个返回元组的函数,或者一个返回一个调用时返回一个namedtuple的函数的函数生成器。它只是改变了容器。你知道吗

我可以自动为类指定属性吗?你知道吗

是的,你可以,正如其他人所回答的:IberêVivek Pandey

相关问题 更多 >