处理(1)一类对象的一般属性和(2)该对象实例的个别属性的最python方法

2024-04-16 20:38:24 发布

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

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

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

具体地说,我正在处理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)}

这是一个字典,其中包含字段的命名元组。”Critical”表示提交中是否需要该字段才能显示,display用于确定是否应打印该字段。你知道吗

我的问题是:我知道python中的相关数据应该以一致的方法进行分组,但我不知道如何在这里这样做:我可以在Commit()类中有一个“指针”,例如self.attr = commit_attr,但这不是很干净,并且依赖于对象保持其地址,即可变,否则,如果我更改了常规属性的值,它将不再与Commit()类相关联。你知道吗


Tags: 数据self苹果falsetruedate属性type
1条回答
网友
1楼 · 发布于 2024-04-16 20:38:24

我不确定这是否对您有帮助,但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属性会同时影响所有实例。你知道吗

相关问题 更多 >