【问题标题】:Python official name for an attribute that is not a method不是方法的属性的 Python 官方名称
【发布时间】:2018-06-17 19:41:16
【问题描述】:

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

class C:

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

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

我相信不同的人可能会调用 val 不同的东西,比如“字段”或“变量”,但我对正式名称感兴趣。

【问题讨论】:

  • 为什么需要正式名称?
  • 如果我想与他人谈论、搜索或以其他方式引用编程语言中的某些结构,我会尽量做到精确。我认为最好的方法是使用官方术语

标签: naming


【解决方案1】:

很难找到有关此主题的官方信息。在阅读了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制作的图表

【讨论】:

    【解决方案2】:

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

    这个命名的特点:

    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 是一个“实例属性”无论它是否可调用。我认为这是你所追求的行为,但我不确定。

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

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

    【讨论】:

    猜你喜欢
    • 2014-10-27
    • 1970-01-01
    • 2012-03-20
    • 1970-01-01
    • 1970-01-01
    • 2016-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多