【问题标题】:What is the difference between a class "Attribute" and "Property"? [duplicate]类“属性”和“属性”有什么区别? [复制]
【发布时间】:2018-04-28 01:30:16
【问题描述】:

有人可以仔细描述“属性”和“属性”之间的细微差别吗?我发现它们有时可以互换使用,并在其他情况下作为区别使用。

【问题讨论】:

    标签: oop properties attributes


    【解决方案1】:

    attributeproperty 术语在大多数情况下是同义词(还有 memberfield),尽管经常使用 propertypythonC#pascal 等)来描述实际由get/set方法实现的“虚拟属性”(attribute用于常规属性)。

    例如(类似python的伪代码):

    class MyClass:
    
        string first_name_attribute;
        string last_name_attribute;
    
        @property
        def full_name(self):
            """Getter method returns the virtual "full name"."""
            return self.first_name_attribute + " " + self.last_name_attribute
    
        @full_name.setter
        def full_name(self, string value):
            """Setter method sets the virtual "full name"."""
            first_name, last_name = value.split(" ")
            self.first_name_attribute = first_name
            self.last_name_attribute = last_name
    

    这里我们有两个“真实”属性 - first_name_attributelast_name_attribute 和一个“虚拟”属性 - full_name

    【讨论】:

      猜你喜欢
      • 2021-12-26
      • 2011-11-14
      • 2021-09-03
      • 1970-01-01
      • 2010-09-20
      • 2015-09-10
      • 1970-01-01
      相关资源
      最近更新 更多