0

This is a pedantic question, but I feel I've been reading some conflicting uses of the term "class attribute" in Python.

My understanding and usage of "attribute" of a class has always been to mean some variable associated with the class, whether it is a class or instance variable.

I've seen some others use "attribute" to mean class/instance variables of a class, as well as methods of that class.

So I wanted to ask if there is a formal definition of what "attribute" means as it pertains to classes in Python?

24n8
  • 1,898
  • 1
  • 12
  • 25
  • 1
    Could we see an example of someone using attribute to refer to a method? That sounds like a mistake to me. – JacobIRR Feb 09 '23 at 16:18
  • In the cases that if refers to a method it could easily be that someone references a function but didn't try call it (and it didn't exist either way) in which case the error would report attribute access even if it was supposed to be a method. Python can't know that. So, please do give an example – roganjosh Feb 09 '23 at 16:20
  • https://docs.python.org/3/glossary.html#term-attribute – buran Feb 09 '23 at 16:21
  • Attributes can be stored on most any object. Both classes and instances are objects, so attributes can be stored on either. An attribute stored on an instance takes precedence over a class attribute of the same name. Methods are indeed attributes of the class (callable ones). – kindall Feb 09 '23 at 16:25
  • @JacobRR, every standard AttributeError message, e.g. when you call non-existing method – buran Feb 09 '23 at 16:25
  • @JacobIRR I may have gotten my OP backwards, but in https://stackoverflow.com/questions/2736255/abstract-attributes-in-python, the top answer has a base class `A` with an attribute `a` but it has a decorator `@abstractmethod`. isn't `a` here an attribute and not a method? – 24n8 Feb 09 '23 at 16:27
  • @JacobRR, check also last paragraph in https://docs.python.org/3/tutorial/classes.html#method-objects _If the name denotes a valid class attribute that is a function object, a method object is created_ Also read next part [Class and Instance variables](https://docs.python.org/3/tutorial/classes.html#class-and-instance-variables) – buran Feb 09 '23 at 16:32

1 Answers1

0

When you say "class/instance variables of a class, as well as methods of that class", there seems to be some confusion here, because methods of a class are class variables of that class.

In Python, functions are first-class objects, as in, they behave just like ints and strings: they can be stored in variables, and edited after being created. So there is no reason why a method of a class should not be considered a class variable, and therefore an attribute of the class.

Lecdi
  • 2,189
  • 2
  • 6
  • 20