大多数pythonic方法来处理(1)一类对象的一般属性(2)该对象的一个​​实例的各个属性

时间:2012-08-22 22:07:01

标签: python class coding-style

首先是一般性解释,然后是我实际工作的内容:假设你有一组苹果。某些属性可以共享,例如type = "Green Apple"picked_date = "Aug 12 2012",但苹果之间的其他数据可能不同,例如is_bruisedweightsize。在type之类的苹果之间共享可编辑值的最pythonic方法是什么,但是对于组中的每个苹果都有单独的属性?来自CC++,我的第一直觉是一般结构,每个苹果的结构都带有指向一般结构的指针,因为每个苹果实例包含组信息似乎很愚蠢,因为如果我想要type = "Red Apple"我必须迭代所有苹果来编辑他们的type值,这会浪费编程能力。

在实际代码中,在我目前的工作项目中,我目前正在开发一个git脚本来帮助以对我公司有意义的方式解析输出。我一直在阅读(a)列表,(b)元组,(c)字典和(d)python中的类,我真的很难找出表示这些数据的最佳方法。

具体来说,我正在处理git提交,我关注的是两种类型的值:所有提交之间共享的常规属性,例如“我打印出提交的作者吗?”和特定属性例如“commit x has author 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)}

这是一个字段,其中包含字段的命名元组。 “严重”表示在提交中是否需要该字段以显示它,显示用于确定是否应该打印。

这是我的问题:我知道python中的相关数据应该用一个连贯的方法分组,但我不知道如何在这里做:我可以有一个“指针”,例如self.attr = commit_attr in Commit()类,但这不是很干净,并且取决于保持其地址的对象,即可变,否则如果我改变了一般属性的值,它将不再与{{1 }。class。

1 个答案:

答案 0 :(得分:2)

我不完全确定这对你有用,但Python有类属性,它们在类实例之间共享:

>>> class A(object):
...   foo = 'bar'  # Notice that this isn't in an __init__ function definition
... 
>>> a = A()        # Just creating two distinct instances of A
>>> b = A()
>>> A.foo = 'baz'  # Now, I'm setting the class attribute
>>> b.foo
'baz'              # Notice how all instances of A changed
>>> a.foo
'baz'
>>> 

编辑class属性会立即影响所有实例。