Python official name for an attribute that is not a method

Question:

According to my understanding the data members of objects in Python are referred to as ‘attributes’.
Attributes that are callable are referred to as an object’s ‘methods’, but I couldn’t find a name for non-callable attributes, such as val in the following example:

class C:

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

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

I am sure different people may call val different things like ‘field’ or ‘variable’ but I am interested in an official name.

Asked By: mrclng

||

Answers:

I’m not sure if one exists, but I’d suggest just “instance attribute”.

Features about this naming:

  1. It excludes methods. Methods are all callable class attributes, so this wording excludes all methods.
  2. It includes callable instance attributes. Consider the following code:
class Container:
    def __init__(self, item):
        self.item = item

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

Note that c.item is an “instance attribute” regardless of whether or not it’s callable. I think this is behaviour you’re after, but I’m not sure.

  1. It excludes non-callable class attributes, e.g.
class SomeClass:
    x = 5  # Is not an "instance attribute"
  1. It includes per-instance attributes, e.g.
obj.x = 5
obj.x  # Is an "instance attribute"

In the end, all of these features may be positives or negatives depending on specifically what you want. But I don’t know specifically what you want, and this is as close as I can get. If you can provide more information, I can give a better suggestion.

Answered By: Quelklef

Surprisingly hard to find official information on this topic. After reading this article I do believe it should simply be called Class Variable and Instance Variable.


Attributes, Properties, Methods and Variables

Attribute is the collection name for the three names Property, Method and Variable. The latter two are prefixed by either Class or Instance. A property can only belong to the 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

Sources

Diagram made in Creately

Answered By: Mandera
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.