Python 不是方法的属性的正式名称

Python official name for an attribute that is not a method

据我了解Python中对象的数据成员被称为'attributes'。 可调用的属性称为对象的 'methods',但我找不到不可调用属性的名称,例如以下示例中的 val

class C:

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

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

我相信不同的人可能会称呼 val 不同的东西,例如 'field' 或 'variable',但我对正式名称感兴趣。

我不确定是否存在,但我建议 "instance attribute"。

这个命名的特点:

  1. 不包括方法。方法都是可调用的class属性,所以这个写法排除了所有方法
  2. 它包括可调用的实例属性。考虑以下代码:
class Container:
    def __init__(self, item):
        self.item = item

c = Container(x)
c.item  # is an "instance attribute"
c.item == x  # True

请注意 c.item 是一个 "instance attribute" 不管 它是否可调用。我认为这是你想要的行为,但我不确定。

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

最终,所有这些功能可能是积极的,也可能是消极的,具体取决于具体您想要什么。但我不知道具体你想要什么,这是我能得到的最接近的。如果你能提供更多的信息,我可以给出更好的建议。

很难找到关于这个主题的官方信息。阅读 this 文章后,我认为它应该简单地称为 Class VariableInstance Variable


特性、属性、方法和变量

Attribute 是三个名称 PropertyMethodVariable 集合名称 。后两者以 ClassInstance 为前缀。一个property只能属于Class.

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

中制作的图表