不是方法的属性的Python官方名称

时间:2018-06-17 19:41:17

标签: naming

根据我的理解,Python中对象的数据成员称为'属性'。 可调用的属性称为对象'方法'但是我无法找到不可调用属性的名称,例如以下示例中的val

class C:

    def __init__(self):
        self.val = 42. # How would this be called?

    def self.action():
        """A method."""
        print(self.val)

我相信不同的人可能会拨打val不同的内容,例如' field'或者'变量'但我对正式名称感兴趣。

2 个答案:

答案 0 :(得分:0)

我不确定是否存在,但我建议只使用“实例属性”。

有关此命名的功能:

  1. 它不包括方法。方法都是可调用的 class 属性,因此这个措辞排除了所有方法。
  2. 它包括可调用的实例属性。请考虑以下代码:
  3. class Container:
        def __init__(self, item):
            self.item = item
    
    c = Container(x)
    c.item  # is an "instance attribute"
    c.item == x  # True
    

    请注意,c.item是一个“实例属性”,无论是否可以调用。我认为这是你所追求的行为,但我不确定。

    1. 它排除了不可调用的类属性,例如
    2. class SomeClass:
          x = 5  # Is not an "instance attribute"
      
      1. 它包括每个实例的属性,例如
      2. obj.x = 5
        obj.x  # Is an "instance attribute"
        

        最后,所有这些功能可能都是正面或负面的,具体取决于具体你想要什么。但我不知道你想要什么,这是我能得到的尽可能接近。如果您能提供更多信息,我可以给出更好的建议。

答案 1 :(得分:0)

令人惊讶地很难找到有关此主题的官方信息。在阅读this文章后,我相信应该将其简称为Class VariableInstance Variable


属性,属性,方法和变量

Attribute是三个名称PropertyMethodVariable的集合名称。后两个前缀为ClassInstanceproperty只能属于Class

enter image description here

class Foo:
    a = 1
    def __init__(self):
        self.b = 2

    @property
    def c(self):
        return 3

    @classmethod
    def d(cls):
        return 4

    def e(self):
        return 5

Foo.a    # Class Attribute:      Class Variable
Foo().a  # Class Attribute:      Class Variable

Foo().b  # Instance Attribute:   Instance Variable

Foo.c    # Class Attribute:      Property

Foo.d    # Class Attribute:      Class Method
Foo().d  # Class Attribute:      Class Method

Foo.e    # Class Attribute:      Class Method
Foo().e  # Instance Attribute:   Instance Method

来源

Creately中制作的图表