【发布时间】:2012-08-22 22:07:00
【问题描述】:
首先是一般性解释,然后是我实际工作的内容:假设您有一组苹果。某些属性可以共享,例如type = "Green Apple" 和picked_date = "Aug 12 2012",但其他数据在苹果之间可能不同,例如is_bruised 和weight 或size。在苹果之间共享 editable 值(例如type)但组中每个苹果都有单独的属性的最pythonic方法是什么?来自C,C++,我的第一直觉是一个通用结构,每个苹果的结构都有一个指向通用结构的指针,因为每个苹果实例包含组信息似乎很愚蠢,因为如果我想要type = "Red Apple" 我必须遍历所有苹果来编辑它们的 type 值,这是对编程能力的浪费。
在实际代码中,在我当前的工作项目中,我目前正在编写一个 git 脚本,以帮助以对我的公司有意义的方式解析输出。我一直在阅读 Python 中的 (a) 列表、(b) 元组、(c) 字典和 (d) 类,我真的一直在努力找出表示这些数据的最佳方式。
具体来说,我正在处理 git 提交,我关心两种类型的值:所有提交之间共享的通用属性,例如“我是否打印出提交的作者?”,以及特定属性例如“提交 x 有作者 y”。我目前的解决方案不优雅:
class Commit(object):
def __init__(self, author="", committer="", date="", issue="",
instruction="", message="", review="", sha="", short=""):
self.author = author
self.committer = committer
self.date = date
self.instruction = instruction
self.issue = issue
self.message = message
self.review = review
self.sha = sha
self.short = short
此类包含与特定提交相关的数据。现在,所有提交的数据都是这样存储的:
Attribute = namedtuple('Attribute', ['display', 'critical'])
commit_attr = {'author': Attribute(display = True, critical = True),
'committer': Attribute(display = True, critical = True),
'date': Attribute(display = False, critical = False),
'instruction': Attribute(display = True, critical = False),
'issue': Attribute(display = True, critical = False),
'message': Attribute(display = True, critical = False),
'review': Attribute(display = True, critical = False),
'sha': Attribute(display = True, critical = True),
'short': Attribute(display = True, critical = True)}
这是一个带有字段命名元组的字典。 “Critical”表示提交中是否需要该字段才能显示,display 用于确定是否应打印。
这是我的问题:我知道python中的相关数据应该以连贯的方法进行分组,但我不知道如何在这里做到:我可以有一个“指针”,例如@中的self.attr = commit_attr 987654334@ 类,但这不是很干净,并且将取决于该对象保持其地址,即可变,否则如果我更改通用属性的值,它将不再与 Commit() 类关联。
【问题讨论】:
标签: python class coding-style